POJ - 2442 Sequence(优先队列/堆)

点我看题

大概今天状态有点不对,有一点烦躁。

题意:给出一个m×n的矩阵,然后从矩阵的每一行跳出1个数可以形成n^m个序列,求出这些序列和中最小的n个。

分析:用优先队列实现,用一个从大到小的临时队列来保存前i行矩阵的最小和,然后不断地更新。

参考代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<iostream>

using namespace std;
#define inf 0x3f3f3f3f
const int maxn = 2e3+5;
const int maxm = 1e2+5;
int m,n;
int num[maxn];
//优先队列默认从大到小
//定义从小到大
priority_queue<int,vector<int>,greater<int> > q;//存放结果
//定义从大到小
priority_queue<int,vector<int>,less<int> > tmp;//存放临时结果

int main()
{
    int T;
    scanf("%d",&T);
    while( T--)
    {
        while( !q.empty())
            q.pop();
        while( !tmp.empty())
            tmp.pop();
        scanf("%d%d",&m,&n);
        for( int i = 1; i <= n; i++)
        {
            int x;
            scanf("%d",&x);
            q.push(x);
        }

        for( int i = 1; i < m; i++)
        {
            for( int j = 1; j <= n; j++)
            {
                scanf("%d",&num[j]);
                tmp.push(inf);//这个初始化很重要的
            }
            sort(num+1,num+1+n);
            while( !q.empty())
            {
                int tp = q.top();
                for( int j = 1; j <= n; j++)
                {
                    if( tp+num[j] < tmp.top())
                    {
                        tmp.pop();//保证tmp的大小恒为n
                        tmp.push(tp+num[j]);
                    }
                    else
                        break;
                }
                q.pop();
            }

            while( !tmp.empty())
            {
                q.push(tmp.top());
                tmp.pop();
            }

        }
        bool flag = 1;
        while( !q.empty())
        {
            if( flag)
            {
                printf("%d",q.top());
                flag = 0;
            }
            else
                printf(" %d",q.top());
            q.pop();
        }
        puts("");
    }

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值