时间限制:3.000秒
题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=3148
有k个整数数组,每个数组中各取一个元素加起来,一共可以得到k的k次方种结果(不考虑相同的数)。求这些数中最小的k个数。k最大为750。
一个一个去算然后排序肯定是要超时的。
引用刘汝佳《算法竞赛入门经典:训练指南》中提供的算法:
只考虑两个有序表的情况,每次各取一个,把n^2个和组织成n个有序表:
表1:A[0] + B[0] <span style="font-family: Arial;">≤</span> A[0] + B[1] <span style="font-family: Arial;">≤ … </span><span style="font-family: Arial;">≤ A[0] + B[n - 1]</span><span style="font-family: Arial;">
</span><pre name="code" class="plain" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 26px;">表2:A[1] + B[0] <span style="font-family: Arial;">≤</span> A[1] + B[1] <span style="font-family: Arial;">≤ … </span><span style="font-family: Arial;">≤ A[1] + B[n - 1]</span>
<span style="font-family: Arial;">……</span>
<pre name="code" class="plain" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 26px;">表n:A[n-1] + B[0] <span style="font-family: Arial;">≤</span> A[n-1] + B[1] <span style="font-family: Arial;">≤ … </span><span style="font-family: Arial;">≤ A[n-1] + B[n - 1]</span>
用二元组(s, b)表示,其中s = A[a] + B[b],s所在的表的的下一个值为s - B[b] + B[b + 1],其中a的值并不需要。
因此就可以用优先队列计算,事先将每个表的第一个元素都放进去,然后每次取最小值,计算下一个值再放回队列即可。
而对于k个表,我们可以实现边读边算,每次将两个表计算出的结果合并到第一个表,将新的数据读入第二个表重复计算即可。假设计算到第i个数组,那么第一个表里就是前i-1个数组每次各取一个的数中最小的k个数,已经是最优的了,那么和第i个数组进行合并后得到的就是前i个数组各取一个的数中最小的k个数,这样算到最后即为所求。
#include
#include
#include
using namespace std;
struct Item {
int s, b; // s = A[a] + B[b]
Item(const int &s, const int &b) : s(s), b(b) {}
bool operator < (const Item &i) const { return s > i.s; }
};
int A[1024], B[1024];
inline void merge(int n) {
priority_queue
que;
for(int i = 0; i != n; ++i) que.push(Item(A[i] + B[0], 0));
for(int i = 0; i != n; ++i) {
Item cur = que.top(); que.pop();
A[i] = cur.s;
if(cur.b + 1 < n) que.push(Item(cur.s - B[cur.b] + B[cur.b + 1], cur.b + 1));
}
}
int main() {
int n;
while(~scanf("%d", &n)) {
for(int i = 0; i != n; ++i) A[i] = 0;
for(int j = 0; j != n; ++j) scanf("%d", &A[j]);
for(int i = 1; i != n; ++i) {
for(int j = 0; j != n; ++j) scanf("%d", &B[j]);
sort(B, B + n);
merge(n);
}
for(int i = 0; i != n; ++i) {
if(i) printf(" ");
printf("%d", A[i]);
}
printf("\n");
}
return 0;
}