大概今天状态有点不对,有一点烦躁。
题意:给出一个m×n的矩阵,然后从矩阵的每一行跳出1个数可以形成n^m个序列,求出这些序列和中最小的n个。
分析:用优先队列实现,用一个从大到小的临时队列来保存前i行矩阵的最小和,然后不断地更新。
参考代码:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn = 2e3+5;
const int maxm = 1e2+5;
int m,n;
int num[maxn];
//优先队列默认从大到小
//定义从小到大
priority_queue<int,vector<int>,greater<int> > q;//存放结果
//定义从大到小
priority_queue<int,vector<int>,less<int> > tmp;//存放临时结果
int main()
{
int T;
scanf("%d",&T);
while( T--)
{
while( !q.empty())
q.pop();
while( !tmp.empty())
tmp.pop();
scanf("%d%d",&m,&n);
for( int i = 1; i <= n; i++)
{
int x;
scanf("%d",&x);
q.push(x);
}
for( int i = 1; i < m; i++)
{
for( int j = 1; j <= n; j++)
{
scanf("%d",&num[j]);
tmp.push(inf);//这个初始化很重要的
}
sort(num+1,num+1+n);
while( !q.empty())
{
int tp = q.top();
for( int j = 1; j <= n; j++)
{
if( tp+num[j] < tmp.top())
{
tmp.pop();//保证tmp的大小恒为n
tmp.push(tp+num[j]);
}
else
break;
}
q.pop();
}
while( !tmp.empty())
{
q.push(tmp.top());
tmp.pop();
}
}
bool flag = 1;
while( !q.empty())
{
if( flag)
{
printf("%d",q.top());
flag = 0;
}
else
printf(" %d",q.top());
q.pop();
}
puts("");
}
return 0;
}