【待完善】UVA-11997:K Smallest Sums

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wingrez/article/details/86655953

UVA-11997:K Smallest Sums

来源:UVA

标签:数据结构、优先队列

参考资料:《算法竞赛入门经典训练指南》P189

相似题目:

题目

You’re given k arrays, each array has k integers. There are k ways to pick exactly one element in each array and calculate the sum of the integers. Your task is to find the k smallest sums among them.

输入

There will be several test cases. The first line of each case contains an integer k (2 ≤ k ≤ 750). Each of the following k lines contains k positive integers in each array. Each of these integers does not exceed 1,000,000. The input is terminated by end-of-file (EOF).

输出

For each test case, print the k smallest sums, in ascending order.

输入样例

3
1 8 5
9 2 5
10 7 6
2
1 1
1 2

输出样例

9 10 12
2 2

解题思路

建议认真参考原书。

参考代码

#include<cstdio>
#include<algorithm>
#include<queue>
#define MAXN 755
using namespace std;

struct Item{
	int s,b;
	Item(int _s,int _b):s(_s),b(_b){}
	bool operator < (const Item& rhs) const{
		return s>rhs.s;
	}
};
int arr[MAXN][MAXN];

void merge(int A[], int B[], int C[], int n){
	priority_queue<Item> 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();
		C[i]=item.s;
		int b=item.b;
		if(b+1<n) q.push(Item(item.s-B[b]+B[b+1], b+1)); 
	}
}

int main(){
	int n;
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				scanf("%d",&arr[i][j]);
			}
			sort(arr[i],arr[i]+n);
		}
		
		for(int i=1;i<n;i++){
			merge(arr[0],arr[i],arr[0],n);
		}
		
		printf("%d",arr[0][0]);
		for(int i=1;i<n;i++){
			printf(" %d",arr[0][i]);
		}
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wingrez/article/details/86655953