UVa 11997 K Smallest Sums priority queue && ordered table && merge

Source: Internet
Author: User

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

Related Article

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.