hdu 3673 David Shopping (优先队列)

本文介绍了一个使用优先队列解决的口袋问题算法。给定一个初始为空的口袋,其容量为m,以及一系列物品,当新物品加入时,根据特定规则决定是否将其放入口袋或替换已有的物品。文章提供了完整的C++实现代码,并详细解释了处理过程中的关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:给定口袋大小m,及一个大小为n的礼品序列,当新礼品加入时,如果相同礼品在口袋中,则该礼品的“平凡程度”+1,如果无相同礼品且有多余空间,则放入,如果无多余空间,则把平凡程度最大的礼物舍弃。若有相同,优先舍弃最早放入口袋中的礼品。求丢了多少次礼品

解析:优先队列处理 注意一些细节


#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 1000005;
#define inf 0x3f3f3f3f
#define maxn 2000100
const int N = 10010;

struct node
{
    int x,val,pos;
    bool operator <(const node & a)const
    {
        return val < a.val || (val == a.val && pos > a.pos);
    }
}st;
int n,m;
int a[maxn],vis[maxn],index[maxn];
priority_queue<node> pq;
int main()
{
    int T,C = 1;
    //scanf("%d",&t);
    while(scanf("%d%d",&m,&n) && (n+m))
    {
        memset(vis,0,sizeof(vis));
        while(!pq.empty())
            pq.pop();
        int ans = 0,num = 0;
        for(int i = 0; i < n; i++)
        {
            int x;
            scanf("%d",&x);
            if(num < m)
            {
                if(!vis[x])
                {
                    st.x = x;
                    st.val = 1;
                    st.pos = i;
                    index[x] = i;
                    num++;
                }
                else
                {
                    st.x = x;
                    st.val = vis[x] + 1;
                    st.pos = index[x];
                }
                vis[x]++;
                pq.push(st);
            }
            else
            {
                if(vis[x])
                {
                    vis[x]++;
                    st.x = x;
                    st.val = vis[x];
                    st.pos = index[x];
                    pq.push(st);
                }
                else
                {
                    while(vis[pq.top().x] != pq.top().val || index[pq.top().x] != pq.top().pos)
                        pq.pop();
                    vis[pq.top().x] = 0;
                    pq.pop();
                    ans++;
                    st.x = x;
                    st.val = 1;
                    st.pos = i;
                    pq.push(st);
                    index[x] = i;
                    vis[x] = 1;
                }
            }
        }
        printf("Case %d: %d\n",C++,ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值