题目链接: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;
}