UVA-11997 K Smallest Sums
Time Limit: 1000MS |
|
Memory Limit: Unknown |
|
64bit IO Format: %lld &%llu |
Submit Status |
You ' re given k-arrays, each with a k integers. There is k^k ways to pick exactly one element with each array and calculate the sum of the integers. Your task is to find the K smallest sums among them.
The question is from here .
My Solution
Sort each array and make an orderly list.
Table 1:a1 + B1 <= a1+b2 <= a1+b3 <= ""
Table 2:a2 + B1 <= ""
Table 3:a3 + B1 <= ""
The element shape of the first table is like Aa + Bb, denoted by (s = aa+bb, b), with s ' = Aa + b (b+1) =aa + bb-bb + b (b+1) = S-bb + b (b+1);
#include <iostream> #include <queue> #include <cstdio> #include <algorithm>using namespace std; const int MAXN = 760;int a[maxn],b[maxn];struct Item {int S, B; Item (int s, int b): s (s), B (b) {} BOOL operator < (const item& RHS) Const {return s > rhs.s; }};void Merge_pro (int* A, int* b, int n) {priority_queue<item> q; for (int i = 0; i < n; i++) Q.push (Item (a[i]+b[0], 0)); for (int i = 0; i < n; i++) {Item item = Q.top (); Q.pop (); A[i] = ITEM.S; int b = ITEM.B; if (B+1 < n) q.push (Item (item.s-b[b]+b[b+1], b+1)); This "If" Judge is really necessary! }}int Main () {int n; while (scanf ("%d", &n) = = 1) {for (int i = 0; i < n; i++) {for (int j = 0; J < N; j + +) { if (i = = 0) scanf ("%d", &a[j]); Else scanf ("%d", &b[j]); } if (i = = 0) sort (A, a+n); else sort (B, b+n); if (i! = 0) mErge_pro (A, B, N); } printf ("%d", a[0]); for (int i = 1; i < n; i++) printf ("%d", a[i]); printf ("\ n"); } return 0;}
Thank you!
UVa 11997 K Smallest Sums priority queue && ordered table && merge