题目链接:https://vjudge.net/problem/UVA-11997
题意:
有k个长度为k的数组,从每个数组中取一个数加在一起得到一个新的数,按照这样操作,问得到的前k个最小的数是什么。
思路:
一共有k^k次方个数,k<=750,直接构造出来不可行。当只存在两个这样的数组的时候,设分别为数组a, b。分别将a,b数组从小到大排序。
可以构造如下:
a1+b1 <= a1+b2 <= a1+b3
a2+b1 <= a2+b2 <= a2+b3
a3+b1 <= a3+b2 <= a3+b3
我们固定a数组,将b[1]与a数组中的各个数相加,得到k个比较小的数,而这k个数中一定存在a, b这两个数组组合后的最小的数a[1]+b[1],我们把这k个组合出来的数取出最小的那个,新加入a[1]+b[1]右边的那个数a[1]+b[2]。在Node中,我们保存了b数组的下标,所以可以求出它的右边一个数。
既然我们求出了两个数组组合后最小的k个数,那么我们可以将得到后的这k个数,与下一个数组组合,以此类推。
代码:
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 750+50;
int a[maxn], b[maxn], n;
struct Node
{
int val, idx;
Node(int val, int idx):val(val), idx(idx){}
bool operator<(const Node &rhs)const{
return this->val > rhs.val;
}
};
void merge(){
priority_queue<Node> pq;
for(int i=0; i<n; ++i){
pq.push(Node(a[i]+b[0], 0));
}
for(int i=0; i<n; ++i){
Node tp = pq.top(); pq.pop();
a[i] = tp.val;
int idx = tp.idx;
if(idx+1<n) pq.push(Node(a[i]-b[idx]+b[idx+1], idx+1));
}
}
int main(){
ios::sync_with_stdio(false);
while(cin>>n){
for(int i=0; i<n; ++i){
cin>>a[i];
}
sort(a, a+n);
for(int i=1; i<n; ++i){
for(int j=0; j<n; ++j){
cin>>b[j];
}
sort(b, b+n);
merge();
}
for(int i=0; i<n; ++i){
if(i) cout<<" ";
cout<<a[i];
}
cout<<endl;
}
return 0;
}