您的位置:首页 > 理论基础 > 数据结构算法

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

2015-08-07 12:08 701 查看
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 = 800 + 10;

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,0,n) Q.push(Node{A[i]+B[0],0});
FOR(i,0,n){
Node u=Q.top();Q.pop();
C[i]=u.s;
int b=u.b;
if(b+1 < n) Q.push(Node{u.s-B[b]+B[b+1],b+1}); //加入A[a][b+1]
}
}

int main(){
int n;
int A[maxn],B[maxn];

while(scanf("%d",&n)==1){
FOR(j,0,n) scanf("%d",&A[j]); sort(A,A+n);
FOR(i,1,n){
FOR(j,0,n) scanf("%d",&B[j]);
sort(B,B+n);
merge(A,B,A,n);
}
printf("%d",A[0]);
FOR(i,1,n)
printf(" %d",A[i]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: