zoukankan      html  css  js  c++  java
  • Codeforces Round #174 (Div. 1) B. Cow Program(dp + 记忆化)

    题目链接:http://codeforces.com/contest/283/problem/B

    思路: dp[now][flag]表示现在在位置now,flag表示是接下来要做的步骤,然后根据题意记忆化搜索记忆,vis数组标记那些已经访问过的状态。

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #define REP(i, a, b) for (int i = (a); i < (b); ++i)
    #define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
    using namespace std;
    
    const int MAX_N = (200000 + 100);
    long long dp[MAX_N][2];
    int vis[MAX_N][2];
    int N, a[MAX_N];
    
    long long dfs(int now, int dir)
    {
        if (now <= 0 || now > N) return 0;
        if (~dp[now][dir]) return dp[now][dir];
        if (vis[now][dir]) return -1;
        vis[now][dir] = 1;
        long long res = dfs(dir ? now + a[now] : now - a[now], dir ^ 1);
        return dp[now][dir] = (res < 0 ? -1 : res + a[now]);
    }
    
    int main()
    {
        while (cin >> N) {
            FOR(i, 2, N) cin >> a[i];
            memset(dp, -1, sizeof(dp));
            memset(vis, 0, sizeof(vis));
            FOR(i, 1, N - 1) {
                long long ans = dfs(i + 1, 0);
                cout << (ans < 0 ? -1 : ans + i) << endl;
            }
        }
        return 0;
    }
    
    


  • 相关阅读:
    F. 数学上来先打表
    LibreOJ β Round #2
    noip飞扬的小鸟
    jxoi2017
    分块算法
    Chino的数列
    cf 613E
    cf 126D
    cf 542E
    cf 512D
  • 原文地址:https://www.cnblogs.com/wally/p/4477072.html
Copyright © 2011-2022 走看看