打地鼠游戏(贪心+优先队列使用)

本文介绍了如何运用贪心算法和优先队列解决打地鼠游戏的问题。通过创建一个结构体并按时间排序,将解决方案分为两种情况:未雨绸缪和抉择。文中详细探讨了这两种情况,并展示了使用升序和降序优先队列的代码实现。

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

万遍红中带点绿,不过学会了一些有技巧吧。

就是会用那个优先队列了。

https://blog.youkuaiyun.com/stand1210/article/details/52464922

这个题就是贪心。

弄一个结构体,在把时间排序一下。

分两部分:

  1. 第一种可能:未雨绸缪  ( t < p [ i ] . t )
  2. 第二种可能:抉择( t > = p [ i ] . t )

讨论两种情况即可:

但是里面用到了优先队列进行维护:

priority_queue< int, vector <int > ,  greater < int > >que; 升序 top:Min

priority_queue< int >que ;降序 top:Max

贴上代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef struct node{
    ll T,x;
    node(ll t=0,ll X=0):T(t),x(X){}
    friend bool operator < (const node & p1, const node & p2){
        return p1.T<p2.T;
    }
}node;
node p[100005];
int main()
{
    priority_queue< ll ,vector<ll> , greater<ll> >que;
    ll n;
    scanf("%lld",&n);
    ll sumT=-1,sum=0;
    for(int i=0;i<n;i++){
        scanf("%lld",&p[i].T);
        sumT=max(sumT,p[i].T);
    }
    for(int i=0;i<n;i++){
        scanf("%lld",&p[i].x);
    }
    sort(p,p+n);
    int cnt=0,t=0;
    for(int i=0;i<n;i++){
        if(t>=p[i].T){
            ll tmp=que.top();
            if(tmp<p[i].x){
                sum+=p[i].x-tmp;
                que.push(p[i].x);
                que.pop();
            }
        }else{
            t++;
            que.push(p[i].x);
            sum+=p[i].x;
        }
    }
    printf("%lld\n",sum);
    return 0;
}

以下是杨哥哥发给我的: 

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<deque>
#include<ctype.h>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<algorithm>
#define INF 0x3f3f3f3f
#define gcd(a,b) __gcd(a,b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define FAST_IO ios::sync_with_stdio(false)
#define mem(a,b) memset(a,b,sizeof(a))
const double PI = acos(-1.0);
const double eps = 1e-6;
const int MAX=1e5+10;
const int mod=1e9+7;
typedef long long ll;
using namespace std;
 
int vis[1000005];
struct node
{
    int t,v;
}p[1000005];
 
int cmp(node a,node b)
{
    return a.v>b.v;
}
 
int main()
{
    int n;
    scanf("%d",&n);
 
    for(int i=1;i<=n;i++)
        scanf("%d",&p[i].t);
    for(int i=1;i<=n;i++)
        scanf("%d",&p[i].v);
 
    sort(p+1,p+1+n,cmp);
 
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        int t=p[i].t;
        while(vis[t]) t--;
 
        if(t)
        {
            vis[t]=1;
            ans+=p[i].v;
        }
    }
 
    cout<<ans<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值