UVa 11997 K Smallest Sums/priority queue

Source: Internet
Author: User

Priority queue

n rows n digits per row Select a sum sum the smallest n

Suppose only 2 rows

Sort each line first

A1 A2 A3 ... an

B1 b2 b3 ... Bn

Put A1 + B1, A2 + b1, A3 + B1,..., an + B1 into the queue

Then take out a minimum (pop) if it is ax + by then put in a ax+b (y+1) (push) until the n is removed and they are stored in array c

Now there are n so can 22 merge the first and second rows merge the results in the third row and merge ....

#include <cstdio> #include <queue> #include <cstring> #include <algorithm> const int MAXN = 800;

using namespace Std;
int A[MAXN][MAXN];
	struct Item {int s; 
	int b;
	Item (int s, int b): s (s), B (b) {} BOOL operator < (const item& RHS) Const {return s > rhs.s;
}	
};

int n;
	 void merge (int* A, int* B, int* C) {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 ();
	 	C[i] = ITEM.S;
	 	int b = ITEM.B; 
	 if (B+1 < n) q.push (Item (item.s-b[b]+b[b+1], b+1)); 
	}} int main () {int i, J; while (scanf ("%d", &n) = = 1) {for (i = 0; i < n; i++) {for (j = 0; J < N; j + +) scanf ("%d", &a[i][
			J]);
		Sort (A[i], a[i]+n);
		} for (i = 1; i < n; i++) merge (A[0], a[i], a[0]);
		printf ("%d", a[0][0]); 
		for (i = 1; i < n; i++) printf ("%d", a[0][i]);
	printf ("\ n");
} 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.