UVA 11997 K Smallest Sums

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个数。

#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)