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
题目大意:给k个数组各含k个整数,求每个数组中取一个元素他们的和最小的前k个。
分析:一共有k的k次方个和,先看只有两个数组的情况(从小到大排好序的)
1 2 3 ...
1 A1+B1<=A1+B2<=A1+B3.....
2 A2+B1<=A2+B2<=A2+B3.....
...........................
若计算两两之和需k的平方次不可取(时间复杂度O(n的平方))
用优先队列找出最小的前k个和(时间复杂度O(nlogn))
由上面的表格知,第一行的k个元素在它所在列中是和最小的,但不是最小的前k个
把第一行的元素放入优先队列中,把队列的顶部元素提取出来,它是队列中最小的(A[a]+B[b])
也是两两之和中未被提取出来的最小的,把与它最相近的即比它大或等于它的(A[a]+B[b+1])
元素放入队列中。
以此类推提取出来的k个元素是最小的前k个。
两两数组合并从而求得最后结果。
#include<iostream> #include<cstdio> #include<algorithm> #include<queue> using namespace std; const int Max=755; int A[Max][Max]; struct Item { int s,b; Item() {} Item(int s,int b):s(s),b(b) {} bool operator < (const Item &a)const{ return a.s<s; } }item; void merge(int *A,int *B,int *C,int n) { priority_queue<Item> pq; int i,b; for(i=0;i<n;i++) pq.push(Item(A[i]+B[0],0)); for(i=0;i<n;i++) { item=pq.top();pq.pop(); C[i]=item.s;b=item.b; if(b+1<n) pq.push(Item(C[i]-B[b]+B[b+1],b+1)); } } int main() { int n,i,j; while(~scanf("%d",&n)) { 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],n); for(i=0;i<n;i++) printf(i?" %d":"%d",A[0][i]); printf(" "); } return 0; }