其他分享
首页 > 其他分享> > Codeforces Round #751 (Div. 2) D. Frog Traveler(DP)

Codeforces Round #751 (Div. 2) D. Frog Traveler(DP)

作者:互联网

题目链接
题意:
你位于地下\(n\)米的井里,位于位置\(i\)时可以向上跳\(0\)~\(a_i\)米,当你跳到位置\(k\)时,你会下降\(b_k\)米,请问最少跳多少次能到达地面。

思路:
逆向枚举,从\(n\)开始跳,每个位置维护向上跳到当前位置的最少次数。对于位置\(j\)可以跳到位置\(i+b_i\)(先跳到位置\(i\)),应满足\(a_j-(j-i)>=0\)。用队列或双端队列保存已经跳到的位置信息\((a_i-i)\)和次数,每次取队首元素,若满足上述条件且当前位置没有更新过,则更新当前位置信息(第一次更新的向上跳的次数一定为最少的),并放入队尾,且当前队首不要丢出,否则直接丢出,因为\(a_j-j+i<0\),则\(a_j-j+i-1\)必小于\(0\)。

code:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
#include <map>
#include <set>

#define fi first
#define se second
#define pb push_back
#define debug(x) cerr << #x << ":" << x << endl;
#define all(x) x.begin(), x.end()
#define lowbit(x) x & -x
#define fin(x) freopen(x, "r", stdin)
#define fout(x) freopen(x, "w", stdout)
#define ull unsigned long long
#define ll long long

const double eps = 1e-5;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1.0);
const int mod = 1e9 + 7;
const int maxn = 3e5 + 10;

using namespace std;

int n, a[maxn], b[maxn];
int dp[maxn], vis[maxn];
int pre[maxn], ppre[maxn], p[maxn];
vector<int> ans;

int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++)scanf("%d", &a[i]);
    for(int i = 1; i <= n; i ++)scanf("%d", &b[i]);

    deque<pair<int, int>> q;
    q.push_back(make_pair(a[n] - n, n));
    memset(dp, inf, sizeof dp), dp[n] = 0;

    for(int i = n - 1; i >= 1; i --){
        int a1 = i + b[i];
        if(dp[a1] == inf){
            while(q.size()){
                auto p = q.front(); q.pop_front();
                if(p.first + i >= 0){
                    dp[a1] = dp[p.se] + 1;
                    q.push_front(p), q.push_back(make_pair(a[a1] - a1, a1));
                    pre[a1] = i, ppre[a1] = p.se;
                    break;
                }
            }
        }
    }
    for(int i = 1; i <= n; i ++) {
        if(i - a[i] <= 0 && a[i] && dp[0] > dp[i] + 1) {
            dp[0] = dp[i] + 1;
            pre[0] = i;
        }
    }
    if(dp[0] == inf)puts("-1");
    else {
        vector<int> ans; ans.pb(0);
        int ret = pre[0];
        while(ret != n){
            ans.pb(pre[ret]);
            ret = ppre[ret];
        }
        reverse(all(ans));
        printf("%d\n", dp[0]);
        for(int k : ans)printf("%d ", k);
    }
    return 0;
}

标签:751,int,Codeforces,Frog,a1,ret,ans,include,dp
来源: https://www.cnblogs.com/lniiwuw/p/15496996.html