POJ 2442 Sequence

 

Sequence
Time Limit: 6000MS   Memory Limit: 65536K
Total Submissions: 5137   Accepted: 1572

Description

Given m sequences, each contains n non-negative integer. Now we may select one number from each sequence to form a sequence with m integers. It's clear that we may get n ^ m this kind of sequences. Then we can calculate the sum of numbers in each sequence, and get n ^ m values. What we need is the smallest n sums. Could you help us?

Input

The first line is an integer T, which shows the number of test cases, and then T test cases follow. The first line of each case contains two integers m, n (0 < m <= 100, 0 < n <= 2000). The following m lines indicate the m sequence respectively. No integer in the sequence is greater than 10000.

Output

For each test case, print a line with the smallest n sums in increasing order, which is separated by a space.

Sample Input

1
2 3
1 2 3
2 2 3

Sample Output

3 3 4

Source

POJ Monthly,Guang Lin
 
//思路:优先队列的应用
//开始之前先说个例题:
 
//
 
 
//例题二:
 
//有了前面2个例题,思路就基本清晰了,然后就是要明白,m个有序表的前n个最小和可由m-1个有序表的qian那个最小和与第m个有序表形成。以此类推,其实就是例二的扩展算法。
开始忘记给他们排序、WA了一次、郁闷!
 

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <vector>
#include <algorithm>
#define N 2003
using namespace std;
struct node
{
    int i;
    int n;
};
struct cmp
{
  bool operator ()(const node&a,const node&b)
  {
      return a.n>b.n;
  }
};
int a[N],b[N],c[N];
int m,n;
int d[N];
void del()
{
    int i;
    for(i=0;i<n;i++)
         d[i]=0;
    node t;
    priority_queue<node,vector<node>,cmp> Q;
    for(i=0;i<n;i++)
    {
        t.i=i;
        t.n=a[i]+b[d[i]];
        Q.push(t);
    }
    int te=n;i=0;
    while(te--)
    {
       t=Q.top();Q.pop();
       c[i++]=t.n;
       t.n=a[t.i]+b[++d[t.i]];
       Q.push(t);
    }
    for(i=0;i<n;i++)
     a[i]=c[i];
}
int main()
{
    int T;
    int i;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&m,&n);
        for(i=0;i<n;i++)
          scanf("%d",&a[i]);
        sort(a,a+n);
        while(--m)
        {
            for(i=0;i<n;i++)
              scanf("%d",&b[i]);
            sort(b,b+n);
            del();
        }
        n--;
     for(i=0;i<n;i++)
       printf("%d ",a[i]);
     printf("%d\n",a[i]);
    }
    return 0;
}

posted on 2012-07-09 23:45  江财小子  阅读(2318)  评论(0编辑  收藏  举报