Priority Queue UVA 11997 K smallest Sums

Source: Internet
Author: User

Topic Portal

Test Instructions: Training guide P189

Analysis: The idea of a complete reference book, K^k table into an orderly table:

Table 1:a1 + B1 <= A1 + B2 <= .... A1 + Bk

Table 2:a2 + B1 <= A2 + B2 <= ... A2 + Bk

.......

Table K:ak + B1 <= Ak + B2 <= ... Ak + Bk

can maintain a K-length array representing the current top-K small number and, when the array of line I is read, First push first, that is the smallest, then can be updated to the second, that is-b[i] + b[i+1]. The logn of the priority queue can be used to get the minimum value of each moment, and the total complexity becomes NLOGN

#include <bits/stdc++.h>using namespace Std;const int N = + 5;int a[n][n];int n;struct P{int V, id; P () {}p (int v, int id): V (v), ID (ID) {}bool operator < (const p&r) Const{return v > r.v;}}; void get_sum (int *a, int *b, int *c) {priority_queue<p> pque;for (int i=1; i<=n; ++i) {Pque.push (P (A[i] + b[1], 1 ));} for (int i=1; i<=n; ++i) {P r = pque.top ();p que.pop (); C[i] = r.v;int id = r.id;if (r.id < N) pque.push (P (R.v-b[id] + b[id+1], id+1));}} int main (void) {while (scanf ("%d", &n) = = 1) {for (Int. I=1; i<=n; ++i) {for (int j=1; j<=n; ++j) {scanf ("%d", & ; a[i][j]);} Sort (a[i]+1, a[i]+1+n);} for (int i=2; i<=n; ++i) {get_sum (a[1], a[i], a[1]);} for (int i=1; i<=n; ++i) {printf ("%d%c", a[1][i], i = = n? ' \ n ': ');}} return 0;}

  

Priority Queue UVA 11997 K smallest Sums

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.