CFgym:Bonuses and Teleports(贪心)

本文介绍了一种通过预处理每个金币最快到达传送门的时间来优化金币收集路径的方法。该方法使用了动态规划的思想,在每次选择中考虑了直接前进或返回传送门再前进两种策略,以达到最短时间收集所有金币的目标。

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


思路:先预处理每个金币最快到达传送门的时间,然后对于金币i,要么从金币i-1位置走过来,要么在金币i-1先回传送门再从传送门走到金币i的位置,选择时间短的即可。

//Reference: Travel_poorly
# include <iostream>
# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <algorithm>
using namespace std;
const int maxn = 2e5+3;
const int INF = 0x7fffffff;
typedef long long  LL;
int a[maxn], b[maxn], c[maxn], d[maxn];
int main()
{
    int n, m;
    scanf("%d%d",&n,&m);
    a[n+1] = INF;
    for(int i=1; i<=n; ++i) scanf("%d",&a[i]);
    for(int i=1; i<=m; ++i) scanf("%d",&b[i]);
    int j=0;
    for(int i=1; i<=m; ++i)
    {
        while(a[j+1] <= b[i]) ++j;
        if(j) c[i] = b[i]-a[j];
        else c[i] = INF;
        if(j<n) d[i] = a[j+1]-b[i];
        else  d[i] = INF;
        c[i] = min(c[i], d[i]);
    }
    LL ans = 0;
    b[0] = b[m+1] = a[1];
    for(int i=1; i<=m+1; ++i)
    {
        LL tmp = abs((LL)b[i-1] - b[i]);
        tmp = min(tmp, LL(c[i-1])+c[i]);
        ans += tmp;
    }
    printf("%lld\n",ans);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值