NOJ [1316] D Minimums of Sum

链接地址:http://ac.nbutoj.com/Problem/view.xhtml?id=1316

多路归并
我们先考虑解决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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值