给定m个序列,每个包含n个非负整数。
现在我们可以从每个序列中选择一个数字以形成具有m个整数的序列。
很明显,我们一共可以得到nm个这种序列, 然后我们可以计算每个序列中的数字之和,并得到nm个值。
现在请你求出这些序列和之中最小的n个值。
输入格式
第一行输入一个整数T,代表输入中包含测试用例的数量。
接下来输入T组测试用例。
对于每组测试用例,第一行输入两个整数m和n。
接下在m行输入m个整数序列,数列中的整数均不超过10000。
输出格式
对于每组测试用例,均以递增顺序输出最小的n个序列和,数值之间用空格隔开。
每组输出占一行。
数据范围
0<m≤1000,
0<n≤2000
输入样例:
1
2 3
1 2 3
2 2 3
输出样例:
3 3 4
思路:
每次将两个序列进行排序,配对。同时为了避免重复,让指针的移动有序化,先移i再移j
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string.h>
using namespace std;
int n,m,a[2005],b[2005],c[2005],heap[2005*4][4],tot;
void up(int p)
{
while(p>=1)
{
if(heap[p][0]<heap[p/2][0]){swap(heap[p],heap[p/2]);p=p/2;}
else break;
}
}
void down(int p)
{
int s=p*2;
while(s<=tot)
{
if(s<tot&&heap[s][0]>heap[s+1][0])s++;
if(heap[p][0]>heap[s][0]){swap(heap[p],heap[s]);p=s;s=p*2;}
else break;
}
}
void insert(int i,int j,int bo)
{
heap[++tot][0]=a[i]+b[j];
heap[tot][1]=i;heap[tot][2]=j;heap[tot][3]=bo;
up(tot);
}
void del()
{
heap[1][0]=heap[tot][0];
heap[1][1]=heap[tot][1];
heap[1][2]=heap[tot][2];
heap[1][3]=heap[tot][3];
tot--;
down(1);
}
int main()
{ int t;cin>>t;
while(t--){
cin>>m>>n;
for(int i=1;i<=n;i++)cin>>a[i];
sort(a+1,a+1+n);
for(int i=2;i<=m;i++)
{
memset(heap,0,sizeof(heap));tot=0;
for(int i=1;i<=n;i++)cin>>b[i];
sort(b+1,b+1+n);
heap[1][0]=a[1]+b[1];
heap[++tot][1]=1;heap[tot][2]=1;heap[tot][3]=0;
for(int j=1;j<=n;j++)
{
c[j]=heap[1][0];
if(heap[1][3]==0)insert(heap[1][1]+1,heap[1][2],0);
insert(heap[1][1],heap[1][2]+1,1);
del();
}
for(int i=1;i<=n;i++)a[i]=c[i];
}
for(int i=1;i<=n;i++)cout<<a[i]<<" ";cout<<endl;
}
return 0;
}