首页 > 代码库 > (DS 《算法竞赛入门经典》)UVA 11997 K Smallest Sums

(DS 《算法竞赛入门经典》)UVA 11997 K Smallest Sums

题目大意:有k个数组,每个数组选取一个数,组成k^k个数。在这k^k个数中选择最小的前k个数


解题思路:

1、如果只有k个数组,那么最后得到的最小的前k个数应该可以由前两个数组得到的最小k个数与第三个数组

按规则运算后得到。


2、如果每个数组只有3个数.那么前两个数组(a:(a0,a1,a2)    b:(b0,b1,b2,a与b数组都已经有序)运算后有的结果矩阵如下:

a0+b0,a0+b1,a0+b2

a1+b0,a1+b1,a1+b2

a2+b0,a2+b1,a2+b2

在这个矩阵中,a0+b0肯定是最小的。如果一个队列里只维持3个最小数,那么下一个产生最小数的位置是

a0+b1.分析如下:

由a1+b1>a1+b0可知,a1+b1及其后面的不可能产生下一个最小数.依照此逻辑可知下一个可能产生最小数的位置

是a0+b1


3、在以下的这种解法中,他并没有算出k^k个结果,它其实质算了n+n个可能产生最小数的结果而已


Problem K

K Smallest Sums

You‘re given k arrays, each array has k integers. There are kk 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.

Input

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). The size of input file does not exceed 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

Rujia Liu‘s Present 3: A Data Structure Contest Celebrating the 100th Anniversary of Tsinghua University
Special Thanks: Yiming Li
Note: Please make sure to test your program with the gift I/O files before submitting!



代码如下:

/*
 * UVA_11997.cpp
 *
 *  Created on: 2014年12月30日
 *      Author: Administrator
 */


#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>


using namespace std;

const int maxn = 758;
int A[maxn][maxn];


struct Item{
	int s,b;
	Item(int s,int b):s(s),b(b){

	}


	bool operator < (const Item& b) const{
		return s > b.s;
	}
};


void merge(int* A,int* B,int* C,int n){
	priority_queue<Item> q;

	int i;
	for(i = 0 ; i < n ; ++i){
		q.push(Item(A[i] + B[0],0));
	}

	for(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) == 1){
		int i;
		int j;


		for(i = 0 ; i < n ; ++i){
			for(j = 0 ; j < n ; ++j){
				scanf("%d",&A[i][j]);
			}

			sort(A[i],A[i]+n);
		}

		for(i = 1 ; i < n ; ++i){
			merge(A[0],A[i],A[0],n);
		}

		printf("%d",A[0][0]);

		for(i = 1 ; i < n ; ++i){
			printf(" %d",A[0][i]);
		}
		printf("\n");
	}

	return 0;
}




(DS 《算法竞赛入门经典》)UVA 11997 K Smallest Sums