Given m sequences, each contains n non-negative integer. Now we may select one number from each sequence to form a sequence with m integers. It’s clear that we may get n ^ m this kind of sequences. Then we can calculate the sum of numbers in each sequence, and get n ^ m values. What we need is the smallest n sums. Could you help us?
Input
The first line is an integer T, which shows the number of test cases, and then T test cases follow. The first line of each case contains two integers m, n (0 < m <= 100, 0 < n <= 2000). The following m lines indicate the m sequence respectively. No integer in the sequence is greater than 10000.
Output
For each test case, print a line with the smallest n sums in increasing order, which is separated by a space.
Sample Input
1
2 3
1 2 3
2 2 3
Sample Output
3 3 4
题意:有m行数列,每行数列有n个值,每行序列中选取一个值可以组成n^m种不同的序列,求前n小的序列和。
大致思路:使用dfs在每层选取一个数去走完所有的可能。再使用优先队列进行剪枝:
先对每行排序,b数组记录第一列从后往前的前缀和,用来计算dfs到该层时的所能到达的最小序列和。
假设遍历到第k层,当前状态所能到达的最小序列和tmp=前面dfs经过的数字和+b[k]。如果tmp大于等于队头值就说明当前状态没有用,所以return剪枝。
遍历完之后和队头比较,如果小于队头,top弹出并塞入这个和。
时间复杂度分析:剪枝完后的dfs总是走优化路(每次走完都能使计算结果更接近答案)。第一次跑的最坏结果大约是1e6,所以dfs最多走1e6条路,而每条路最多有100个点,所以最多跑1e8次。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod=998244353;
void IOS()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
int a[107][2007],m,n,b[107];
priority_queue<int,vector<int>,less<int>>q;
void dfs(int x,int sum)
{
if(x==m+1)
{
if(q.size()<n)q.emplace(sum);
else
{
q.pop();
q.emplace(sum);
}
return;
}
if(q.size()==n&&sum+b[x]>=q.top())return;
for(int i=1;i<=n;i++)
{
if(q.size()<n||q.top()>sum+a[x][i])dfs(x+1,sum+a[x][i]);
}
}
void solve()
{
cin>>m>>n;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
cin>>a[i][j];
}
sort(a[i]+1,a[i]+1+n);
}
b[m+1]=0;
for(int i=m;i>=1;i--)
{
b[i]=a[i][1]+b[i+1];
}
dfs(1,0);
vector<int>v;
while(!q.empty())
{
v.emplace_back(q.top());
q.pop();
}
for(int i=v.size()-1;i>=0;i--)
{
cout<<v[i];
if(i!=0)cout<<' ';
}
cout<<'\n';
}
int main()
{
IOS();
int T=1;
cin>>T;
while(T--)
{
solve();
}
}