多路归并
我们先考虑解决2路合并问题。对于有序数组a, b,可以维护一个优先队列,元素为a[i] + b[j]。先将a[i] + b[1]入队,取出最大元素后改变元素为a[i] + b[j + 1]。对于n路合并,依次2路合并即可。
出题代码:
#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
struct item
{
int s, p;
item(int ns, int np)
{
s = ns;
p = np;
}
bool operator <(const item& a) const
{
return s > a.s;
}
};
int a[455][455];
int n;
void merge(int pos)
{
priority_queue<item> pr_q;
item t(0, 0);
int rt[455];
for (int i = 1; i <= n; i++)
pr_q.push(item(a[1][i] + a[pos][1], 1));
for (int i = 1; i <= n; i++)
{
t = pr_q.top();
pr_q.pop();
rt[i] = t.s;
if (t.p != n)
{
t.s = t.s - a[pos][t.p] + a[pos][t.p + 1];
t.p++;
pr_q.push(t);
}
}
memcpy(a[1], rt, sizeof(rt));
}
int main()
{
//freopen("data.in", "r", stdin);
//freopen("data.out", "w", stdout);
while (~scanf("%d",&n))
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &a[i][j]);
for (int i = 1; i <= n; i++)
sort(&a[i][1], &a[i][n+1]);
for (int i = 2; i <= n; i++)
merge(i);
for (int i = 1; i < n; i++)
printf("%d ", a[1][i]);
printf("%d\n", a[1][n]);
}
return 0;
}