D - K Smallest Sums(多路归并+贪心)

Problem K

K Smallest Sums

You're given k arrays, each array has k integers. There are kk ways to pick exactly one element in each array and calculate the sum of the integers. Your task is to find the k smallest sums among them.

Input

There will be several test cases. The first line of each case contains an integer k (2<=k<=750). Each of the following k lines contains k positive integers in each array. Each of these integers does not exceed 1,000,000. The input is terminated by end-of-file (EOF). The size of input file does not exceed 5MB.

Output

For each test case, print the k smallest sums, in ascending order.

Sample Input

3
1 8 5
9 2 5
10 7 6
2
1 1
1 2

Output for the Sample Input

9 10 12
2 2

Rujia Liu's Present 3: A Data Structure Contest Celebrating the 100th Anniversary of Tsinghua University
Special Thanks: Yiming Li
Note: Please make sure to test your program with the gift I/O files before submitting!

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <string>
 7 #include <vector>
 8 #include <stack>
 9 #include <queue>
10 #include <set>
11 #include <map>
12 #include <list>
13 #include <iomanip>
14 #include <cstdlib>
15 #include <sstream>
16 using namespace std;
17 typedef long long LL;
18 const int INF=0x5fffffff;
19 const double EXP=1e-6;
20 const int MS=800;
21 int ans[MS],a[MS],n;
22 struct node
23 {
24     int s,b;
25     node(int s,int b):s(s),b(b){}
26     bool operator <(const node &a)const
27     {
28         return s>a.s;
29     }
30 };
31 
32 void merge(int *A,int *B,int *C,int n)
33 {
34     priority_queue<node> pq;
35     for(int i=0;i<n;i++)
36         pq.push(node(A[i]+B[0],0));
37     for(int i=0;i<n;i++)
38     {
39         node t=pq.top();
40         pq.pop();
41         C[i]=t.s;
42         int b=t.b;
43         if(b+1<n)
44             pq.push(node(t.s-B[b]+B[b+1],b+1));
45     }
46 }
47 
48 int main()
49 {
50     while(scanf("%d",&n)!=EOF)
51     {
52         for(int i=0;i<n;i++)
53             scanf("%d",&ans[i]);
54         sort(ans,ans+n);
55         for(int i=1;i<n;i++)
56         {
57             for(int j=0;j<n;j++)
58                 scanf("%d",&a[j]);
59             sort(a,a+n);
60             merge(ans,a,ans,n);
61         }
62         for(int i=0;i<n;i++)
63         {
64             if(i)
65                 printf(" ");
66             printf("%d",ans[i]);
67         }
68         printf("\n");
69     }
70     return 0;
71 }

 

posted @ 2015-03-15 12:15  daydaycode  阅读(201)  评论(0编辑  收藏  举报