UVA 11997 K Smallest Sums
2013-08-31 13:59
302 查看
You're given k arrays, each array has k integers. There are kkways to pick exactly one element in each array and calculate the sum of theintegers. Your task is to find the k smallest sums among them.
Input
There will be several test cases. The first line of each case contains aninteger k (2<=k<=750). Each of the following k lines contains k positiveintegers in each array. Each of these integers does not exceed 1,000,000. Theinput is terminated
by end-of-file (EOF). The size of input file does notexceed 5MB.
Output
For each test case, print the k smallest sums, in ascending order.
Sample Input
3
1 8 5
9 2 5
10 7 6
2
1 1
1 2
Output for the Sample Input
9 10 12
2 2
题目简介:给一个数k。接着给一个k*k的矩阵。每行选一个数相加得到一个数。找出其中得到的数中最小的前k个数。
方法:将第0行和第i行(i>=1)相加,同时取最小的的前k个保存在第0行里。这样就保证了最后得到的第0行的前k个数一定是最小的前k个数。
Input
There will be several test cases. The first line of each case contains aninteger k (2<=k<=750). Each of the following k lines contains k positiveintegers in each array. Each of these integers does not exceed 1,000,000. Theinput is terminated
by end-of-file (EOF). The size of input file does notexceed 5MB.
Output
For each test case, print the k smallest sums, in ascending order.
Sample Input
3
1 8 5
9 2 5
10 7 6
2
1 1
1 2
Output for the Sample Input
9 10 12
2 2
题目简介:给一个数k。接着给一个k*k的矩阵。每行选一个数相加得到一个数。找出其中得到的数中最小的前k个数。
方法:将第0行和第i行(i>=1)相加,同时取最小的的前k个保存在第0行里。这样就保证了最后得到的第0行的前k个数一定是最小的前k个数。
#include<queue> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int num[1000][1000]; int n; void merge(int x) { priority_queue<int> q; for(int i = 0;i < n;i++) { q.push(num[0][i] + num[x][0]); } for(int i = 0;i<n;i++) { for(int j = 1;j<n;j++) { if(num[0][i] + num[x][j] < q.top()) { q.pop(); q.push(num[0][i] + num[x][j]); } else { break; } } } int k = n - 1; while(!q.empty()) { num[0][k--] = q.top(); q.pop(); } }; int main() { while(scanf("%d",&n)!=EOF) { for(int i = 0;i<n;i++) { for(int j = 0;j<n;j++) { scanf("%d",&num[i][j]); } sort(num[i],num[i]+n); } for(int i = 1;i < n;i++) { merge(i); } for(int i = 0;i < n-1;i++) { printf("%d ",num[0][i]); } printf("%d\n",num[0][n-1]); } return 0; }
相关文章推荐
- 【优先队列之多路合并】UVA - 11997 K Smallest Sums
- UVA 11997 K Smallest Sums
- UVa - 11997 - K Smallest Sums
- UVA 11997 K Smallest Sums(优先队列)
- (DS 《算法竞赛入门经典》)UVA 11997 K Smallest Sums
- UVa 11997 K Smallest Sums
- UVA - 11997 K Smallest Sums
- UVA 11997 - K Smallest Sums(优先队列+多路合并)
- UVa - 11997 - K Smallest Sums贪心多路归并
- uva 11997 K smallest sums (优先队列 多路归并)
- UVA 11997 K Smallest Sums
- UVa 11997 (优先队列 多路归并) K Smallest Sums
- UVA - 11997:K Smallest Sums
- UVA - 11997 K Smallest Sums
- UVa 11997 K Smallest Sums
- uva 11997 - K Smallest Sums
- Uva 11997 - K Smallest Sums(多路归并)
- UVA 11997 - K Smallest Sums
- 【暑假】[实用数据结构]UVa11997 K Smallest Sums
- UVA 11997 K Smallest Sums