poj 2442

来源:互联网 发布:考研数学文都网络课程 编辑:程序博客网 时间:2024/06/18 02:05

Sequence
Time Limit: 6000MS
Memory Limit: 65536KTotal Submissions: 8625
Accepted: 2846

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

12 31 2 32 2 3

Sample Output

3 3 4

大致题意:题目输入的第一行T指的是共几个例子,下面每个例子第一行给出两个数据:m,n。接下来输入m行n列,要求求出从每行取出一个数(共m个数)之和的前n个最小和。


思路:这里就不记录原来错误的思路了==写了一大堆还WA了。。。。总之是后来搜了下别人的思路(网址:http://blog.csdn.net/mmc2015/article/details/50490027)用的优先队列,贪心的算法(每次都选择小的)。

具体实现是这样的:建立一个优先队列pq(最大的数优先)。首先输入数据,每行从小到大排列,第一行排序后存在一个临时数组tmp里面,接着开始循环,好多个循环==最外层:从第二行开始循环,行数逐渐增加,每到一个新的行,先将这行的第一个数和tmp里的每一个数加起来,放到优先队列里面。接着开始从这一行的第二个数开始遍历,每到一个新的数,就将这个数和tmp里的每一个数都加起来,然后和优先队列里的top比较,如果小于top,说明这个数更优,就将优先队列的top去掉,把这个数放进去,如果大于top就直接break掉,因为tmp已经是递增的了,后面的必然是大于top的。该行结束以后,将优先队列里的数保存到tmp里面,接着进行下一行。。。以此类推


思路有了这个代码不难写,就是多了几个循环。。写的时候一直担心超时,最后竟一遍就过了==

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>#include <queue>using namespace std;int a[101][2001],tmp[2001];priority_queue<int,vector<int>,less<int> > pq;int main(){    int T,m,n,i,j,k,t,l;    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&m,&n);        for(i=0;i<m;i++)        {            for(j=0;j<n;j++)            {                scanf("%d",&a[i][j]);                if(i==0)tmp[j]=a[i][j];            }            sort(a[i],a[i]+n);        }        sort(tmp,tmp+n);        for(i=1;i<m;i++)        {            for(k=0;k<n;k++)            {                pq.push(a[i][0]+tmp[k]);            }            for(j=1;j<n;j++)            {                for(k=0;k<n;k++)                {                    t=pq.top();                    if(a[i][j]+tmp[k]<=t)                    {                        pq.pop();                        pq.push(a[i][j]+tmp[k]);                    }                    else break;                }            }            l=0;            while(!pq.empty())            {                tmp[l++]=pq.top();                pq.pop();            }            sort(tmp,tmp+n);        }        printf("%d",tmp[0]);        for(i=1;i<n;i++)            printf(" %d",tmp[i]);        printf("\n");    }    return 0;}

这题应该还有其他方法,以后会更新改进



























0 0
原创粉丝点击