您的位置:首页 > 其它

UVA 11997 K Smallest Sums(多路合并)

2016-10-20 18:36 232 查看
这里先把每个序列排序,然后依次和a[1]这个序列合并,那么a[1]这个序列中放的就是最终的结果了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define ss(x) scanf("%d",&x)
const int maxn=768;
int k;
struct node{
int s,b;
node(int s,int b): s(s),b(b) {}
bool operator < (const node &rhs) const {
return s>rhs.s;
}
};
void merge(int *A,int *B,int *C)
{
priority_queue<node> pq;
rep(i,1,k) pq.push(node(A[i]+B[1],1));
rep(i,1,k){
node tmp=pq.top();pq.pop();
C[i]=tmp.s;
int b=tmp.b;
if(b+1<=k) pq.push(node(tmp.s-B[b]+B[b+1],b+1));
}
}
int a[maxn][maxn];
int main()
{
while(ss(k)!=EOF)
{
rep(i,1,k){
rep(j,1,k) ss(a[i][j]);
sort(a[i]+1,a[i]+1+k);
}
rep(i,2,k) merge(a[1],a[i],a[1]);
rep(i,1,k) printf("%s%d",(i==1)?"":" ",a[1][i]);printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: