Gym 101116A K路归并

传送门

K路归并:

 将k个已经排序的数组归并成一个大的排序的结果数组。这些数组可能数量比较大,以至于不能直接装载到内存中。


#include <stdio.h>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
#include <set>
#include <string>
#include <map>
#include <climits>
#include <bitset>
#include <ctime>
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef double db;
const int maxn = 1e2 + 5;
const int mod = 1e9 + 7;
const int INF = 1e8 + 5;
const ll inf = 1e15 + 5;
const db eps = 1e-8;
const ll hp = 2333;
const ll base = 1e9+13;

int a[maxn][maxn], num[maxn];
int n, k;

struct opt
{
	int w, x, y;
	bool operator < (const opt &R) const
	{
		return w > R.w;
	}
};

vector<int> W;

void mer(vector<int> &V, int idx)
{
	priority_queue<opt> Q;
	for (int i = 1; i <= num[idx]; i++)
	{
		Q.push((opt)
		{
			V[0] + a[idx][i], i, 0
		});
	}
	W.resize(0);
	while (W.size() < k && !Q.empty())
	{
		auto it = Q.top();
		Q.pop();
		W.push_back(it.w);
		if (it.y + 1 < V.size())
		{
			++it.y;
			Q.push((opt)
			{
				a[idx][it.x] + V[it.y], it.x, it.y
			});
		}
	}
	V = W;
}

void solve()
{
	cin >> n >> k;
	vector<int> ans;
	ans.push_back(0);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", num + i);
		for (int j = 1; j <= num[i]; j++)
			scanf("%d", &a[i][j]);
		mer(ans, i);
	}
	for (int i = 0; i < k; i++)
		printf("%d%c", ans[i], " \n"[i == k-1]);
}

int main()
{
	int t = 1, cas = 1;
	//freopen("in.txt", "r", stdin);
	// freopen("out.txt", "w", stdout);
	scanf("%d", &t);
	while(t--)
	{
		//  printf("Case #%d:", cas++);
		solve();
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值