【暑假】[实用数据结构]UVa11997 K Smallest Sums

时间:2021-08-16 23:26:20

UVa11997 K Smallest Sums

 题目:

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 ------------------------------------------------------------------------------------------------------------------------------------------------------------------

思路:

 先思考2个有序表(sort后)AB合成的情况。组织如下

【 表】1: A1+B1 <=  A1+B2 <=  A1+B3 <=......

【表】2:A2+B1 <=  A2+B2 <=  A2+B3 <=......

......

【表】n:An+B1 <=  An+B2 <=  An+B3 <=......

转化为多路归并问题且有总数限制为k,因此将n个【表】合并为一个有序【表】C且表中数据数目为k。优先队列处理:初始化优先队列为n个表的第一元素,每次在队列中取出最小元素加入C并将该最小元素在【表】中的后一个元素入队。共取k个元素。

对于k个有序表的情况:两两合并。

于是有代码如下:

 #include<cstdio>
#include<algorithm>
#include<queue>
#define FOR(a,b,c) for(int a=(b);a<(c);a++)
using namespace std; const int maxn = + ; struct Node{
int s,b;
bool operator <(const Node& rhs) const{ //相反定义 <
return s>rhs.s;
}
}; void merge(int* A,int* B,int*C,int n){ //合并AB数组取其前n小的和放入C
priority_queue<Node> Q;
FOR(i,,n) Q.push(Node{A[i]+B[],});
FOR(i,,n){
Node u=Q.top();Q.pop();
C[i]=u.s;
int b=u.b;
if(b+ < n) Q.push(Node{u.s-B[b]+B[b+],b+}); //加入A[a][b+1]
}
} int main(){
int n;
int A[maxn],B[maxn]; while(scanf("%d",&n)==){
FOR(j,,n) scanf("%d",&A[j]); sort(A,A+n);
FOR(i,,n){
FOR(j,,n) scanf("%d",&B[j]);
sort(B,B+n);
merge(A,B,A,n);
}
printf("%d",A[]);
FOR(i,,n)
printf(" %d",A[i]);
printf("\n");
}
return ;
}