UVa 11997 K Smallest Sums (优先队列 & k路归并化为两两归并)

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=497&page=show_problem&problem=3148


思路:k路归并化为两两归并


完整代码:

/*0.172s*/

#include
using namespace std;
const int maxn = 755;

int A[2][maxn];

struct Item
{
	int s, b; /// s=A[a]+B[b],这里的a并不重要,因此不保存
	Item(int s, int b): s(s), b(b) {}
	bool operator < (const Item& rhs) const
	{
		return s > rhs.s; ///最小堆
	}
};

void merge(int* A, int* B, int* C, int n)
{
	priority_queue q; ///最小堆
	for (int i = 0; i < n; i++)
		q.push(Item(A[i] + B[0], 0));
	for (int i = 0; i < n; i++)
	{
		Item item = q.top();
		q.pop();/// 取出A[a]+B[b]
		C[i] = item.s;
		int b = item.b;
		if (b + 1 < n) q.push(Item(item.s - B[b] + B[b + 1], b + 1)); /// 加入A[a]+B[b+1]=s-B[b]+B[b+1]
	}
}

int main()
{
	int n;
	while (~scanf("%d", &n))
	{
		for (int j = 0; j < n; j++) scanf("%d", &A[0][j]);
		sort(A[0], A[0] + n);
		for (int i = 1; i < n; i++) /// 将原问题化成两两合并
		{
			for (int j = 0; j < n; j++) scanf("%d", &A[1][j]);
			sort(A[1], A[1] + n);
			merge(A[0], A[1], A[0], n);
		}
		printf("%d", A[0][0]);
		for (int i = 1; i < n; i++)
			printf(" %d", A[0][i]);
		putchar(10);
	}
	return 0;
}

你可能感兴趣的:(acm之路--好题/陷阱,acm之路--数据结构,UVa,优先队列)