Sequence Poj2442 (堆/优先队列)

这篇博客介绍了POJ2442题目,重点讨论了如何利用优先队列(堆)解决序列问题。内容包括问题描述、输入输出格式以及样例解析,帮助读者理解并实现算法。
摘要由CSDN通过智能技术生成

Sequence

Time Limit: 6000MS Memory Limit: 65536K
Total Submissions: 9136 Accepted: 3040

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


///2442
/// 题目意思就是给你一个n*m的矩阵 每行拿出来一个元素一共组成 n^m个数字求最小的m个数字
///下文m n混了...不影响实际.....
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

const int maxn=2222;
int n,m;
int mod[maxn],num[maxn];

void Find()
{
    priority_queue <int> q; ///利用优先队列维护mod数组 即答案序列
    int i,j;

    for (i=1; i<=m; i++)
    {
        q.push(mod[i]+num[1]); ///将num序列最小的放进去 "模板"
    }

    for (i=1; i<=m; i++)
    {
        for (j=2; j<=m; j++)
        {
            int x=mod[i]+num[j]; ///遍历加和
            if(x<q.top())
            {
                q.pop();
                q.push(x);
            }
            else
            {
                break;///从小到大排序 所以第一个小的不符合后面就不用看了
            }
        }
    }

    for (i=m; i>=1; i--) /// 因为大的优先级高 所以倒序存入mod继续参加之后的加和过程
    {
        mod[i]=q.top();
        q.pop();
    }
}

int main()
{
    int t,i,j;
    cin>>t;
    while (t--)
    {
        cin>>n>>m;
        for(i=1; i<=m; i++)
        {
            cin>>mod[i];
        }
        sort(mod+1,mod+1+m); ///从小到大排序

        for (i=1; i<n; i++)
        {
            for (j=1; j<=m; j++)
            {
                cin>>num[j];
            }
            sort(num+1,num+1+m); ///排序
            Find();
        }

        for (i=1; i<m; i++)
        {
            cout<<mod[i]<<" ";
        }
        cout<<mod[m]<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值