Sequence(優先キュー、またはスタック)
Description
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
Sample Output
全体的なアルゴリズム:
2行ごとのn個の最小値の和を求め,最後の行まで求める.
もちろん優先キューでやることもできます.
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
全体的なアルゴリズム:
2行ごとのn個の最小値の和を求め,最後の行まで求める.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int times;
cin >> times;
while (times--)
{
int m, n;
cin >> m >> n;
vector<int>res(n);
for (int i = 0; i < n; i++)
cin >> res[i];
vector<int>newl(n);
int cop = m-1;
while (cop--)
{
for (int i = 0; i < n; i++)
cin >> newl[i];
sort(newl.begin(), newl.end());
make_heap(res.begin(), res.end()); //make_heap
vector<int>oldl(res.begin(), res.end());
sort(oldl.begin(), oldl.end());
for (int i = 0; i < n; i++)
res[i] += newl[0]; //
for (int w = 1; w < n; w++)
{
bool ex = true;
for (int q =0; q<n ; q++)
{
int tem = newl[w] +oldl[q]; // ,
if (tem < res[0])
{
ex = false;
pop_heap(res.begin(), res.end()); //
res.pop_back(); //
res.push_back(tem);
push_heap(res.begin(), res.end()); //
}
else
break;
}
if (ex)
break;
}
}
sort(res.begin(), res.end());
for (int i = 0; i != n-1; i++)
{
cout <<res[i] << ' ';
}
cout <<res[n - 1] << endl;
}
}
もちろん優先キューでやることもできます.