K Smallest Sums

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

代码:
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std ;
#define M 800
int b[M] ;
int sum[M*M] ;
struct node
{
    int sum , id ;
    bool friend operator<( node a , node b )
    {
        return a.sum > b.sum ;
    }
} ;
priority_queue<node> q , p ;
int main()
{
    int i , j , n , m ;
    int len , v ;
    node now ;
    while( scanf( "%d" , &n ) != EOF )
    {
        for( i = 1 ;i <= n ; i++)
        {
            scanf( "%d" , &now.sum ) ;
            q.push( now ) ;
        }
        for( j = 2; j <= n ;j++){
        
            for( i = 1; i <= n; i++)
                scanf( "%d" , &b[i] ) ;
            sort( b + 1 , b + 1 + n ) ; 
            while( !p.empty() )
                p.pop( ) ;
            while( !q.empty() )
            {
                now = q.top() ;q.pop() ;
                now.id = 1 ; //这里的id意思是所有和第几个相加
                now.sum += b[1] ;
                p.push( now ) ;
                     
            }
            while( q.size( ) < n )
            {
                q.push( p.top() ) ;
                now = p.top() ;// 当前最小的要往后走
                now.sum = now.sum - b[now.id] + b[now.id + 1] ;
                now.id++ ;// 往后面走
                p.pop() ;
                p.push( now ) ;
            }
    
        }
        len = 0 ;
        while( !q.empty() )
        {
            now = q.top() ;q.pop() ;
            b[len++] = now.sum ;
        }
        for( i = 0 ; i < len - 1 ; i++)
            printf( "%d " , b[i] ) ;
        cout << b[len-1] << endl ;
    }

}
原文地址:https://www.cnblogs.com/20120125llcai/p/3072641.html