UV-11997-K Smallest Sums

Source: Internet
Author: User

Enter a number k (2 <= k <= 750), and then enter a matrix of k * k. The element is a positive integer not greater than 1,000,000, each row of k rows is summed up by a number, and the first k and the smallest sum are obtained. --> If the sum of k numbers is the smallest, then the two numbers in any two rows are also the smallest. Otherwise, we can find a smaller number than this value, you can calculate the k smallest sum in the two rows first, and then Merge multiple rows. [Cpp] # include <iostream> # include <algorithm> # include <queue> using namespace std; const int maxn = 750 + 10; // each row may have A maximum of 750 struct items // define the node type {int s; // s = A [I] + B [j] int B; // B = j is the subscript Item (int ss, int bb) of B [j]: s (ss), B (bb) {} bool operator <(const Item & e) const // overload operator, so that the elements in the priority queue are ranked from small to large by the value of s {return s> e. s ;}}; void merge (int * A, int * B, int k) // merge table A and table B, that is, the minimum k and {int I; priority_queue <Item> pq; for (I = 0; I <k; I ++) When k = 2 are obtained) // The first column of elements is entered into the column pq. push (Item (A [I] + B [0], 0); for (I = 0; I <k; I ++) // find the minimum k and {Item item = pq. top (); // retrieve the smallest pq in the queue. pop (); A [I] = item. s; int B = item. b; if (B + 1 <k) // if it is not the last one, add it to the column "1" to remove pq. push (Item (item. s-B [B] + B [B + 1], B + 1) ;}} int a [maxn] [maxn]; // input k * k array int main () {int k, I, j; while (cin> k) {for (I = 0; I <k; I ++) {for (j = 0; j <k; j ++) cin> a [I] [j]; sort (a [I], a [I] + k); // sorting order} for (I = 1; I <k; I ++) merge (a [0], a [I], k); // merge for (I = 0; I <K-1; I ++) // output result cout <a [0] [I] <""; cout <a [0] [k-1] <endl;} return 0 ;}

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.