POJ 2442(优先队列 k路归并 堆)

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
 

 

题目大意

给定n个序列,每个序列长度为m,在每个序列中各取一个数并求和,输出前m小的和

解题思路

共n*m种取法,显然是个求k小堆的问题,但我用了优先队列直接写了,不过据说,二分比优先队列快好多...

贡献些数据吧:

10 10
21 12 123 3 21 123 32 143 43 56
2 32 43 34 54 56 656 76 43 234
234 45 5 65 56 76 43 23 435 57
32 324 435 46 56 76 87 78 43 23
3 32 324 45 56 57 34 23 54 565
23 32 34 342 324 232 2 432 324 12
234 324 4 45 65 67 435 23 5 654
34 3245 345 56 56 657 67 456 345 325
234 234 546 65 88 66 53 654 65 765
5 3 34 34 34 56 345 234 2 34
答案是:131 132 132 133 134 135 140 140 141 141

AC代码:

 

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int a[3003],num[3003],n,m,t;
void solve()
{
    priority_queue<int >q;
    for(int i=0;i<m;i++)    q.push(a[i]+num[0]);///将num序列最小的放进去
    for(int i=0;i<m;i++)
        for(int j=1;j<m;j++)
        {
            int x=a[i]+num[j];///遍历加和  
            if(x<q.top()) q.push(x),q.pop();
            else    break;///从小到大排序 所以第一个小的不符合后面就不用看了  
        }
    for(int i=m-1;i>=0;i--) /// 因为大的优先级高 所以倒序存入a继续参加之后的加和过程  
    {
        a[i]=q.top(); q.pop();
    }
}
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        for(int i=0;i<m;i++)    scanf("%d",&a[i]);
        sort(a,a+m);
        for(int i=1;i<n;i++)
        {
            for(int j=0;j<m;j++)    cin>>num[j];
            sort(num,num+m);
            solve();
        }
        for(int i=0;i<m;i++)    printf("%d%c",a[i],i==m-1?'\n':' ');
    }
    return 0;
}

 

 

 




 

转载于:https://www.cnblogs.com/weimeiyuer/p/8366680.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值