【CF】174 Div.1 B Cow Program

思路是树形DP+状态压缩。其实仅有2个状态,奇数次来到x或者偶数次来到x。(因为对x的更新不同)。
同时开辟visit数组,解决环。注意,一旦遇到环结果就是-1。DP数组存放第奇数/偶数次来到x时,对y的改变两。

  1 /* 283B */
  2 #include <iostream>
  3 #include <string>
  4 #include <map>
  5 #include <queue>
  6 #include <set>
  7 #include <stack>
  8 #include <vector>
  9 #include <deque>
 10 #include <algorithm>
 11 #include <cstdio>
 12 #include <cmath>
 13 #include <ctime>
 14 #include <cstring>
 15 #include <climits>
 16 #include <cctype>
 17 #include <cassert>
 18 #include <functional>
 19 #include <iterator>
 20 #include <iomanip>
 21 using namespace std;
 22 //#pragma comment(linker,"/STACK:102400000,1024000")
 23 
 24 #define sti                set<int>
 25 #define stpii            set<pair<int, int> >
 26 #define mpii            map<int,int>
 27 #define vi                vector<int>
 28 #define pii                pair<int,int>
 29 #define vpii            vector<pair<int,int> >
 30 #define rep(i, a, n)     for (int i=a;i<n;++i)
 31 #define per(i, a, n)     for (int i=n-1;i>=a;--i)
 32 #define clr                clear
 33 #define pb                 push_back
 34 #define mp                 make_pair
 35 #define fir                first
 36 #define sec                second
 37 #define all(x)             (x).begin(),(x).end()
 38 #define SZ(x)             ((int)(x).size())
 39 #define lson            l, mid, rt<<1
 40 #define rson            mid+1, r, rt<<1|1
 41 
 42 const int maxn = 2e5+5;
 43 int a[maxn];
 44 __int64 dp[maxn][2];
 45 bool visit[maxn][2];
 46 int n;
 47 
 48 __int64 dfs(int x, int d) {
 49     if (x<=0 || x>n)
 50         return 0;
 51     
 52     if (dp[x][d] != 0)
 53         return dp[x][d];
 54     
 55     if (visit[x][d]) {
 56         dp[x][d] = -1;
 57         return -1;
 58     }
 59     
 60     visit[x][d] = true;
 61     int x_ = d ? x + a[x] : x - a[x];
 62     int d_ = !d;
 63     __int64 ret = dfs(x_, d_);
 64     
 65     ret = ret < 0 ? -1 : ret + a[x];
 66     dp[x][d] = ret;
 67     
 68     return ret;
 69 }
 70 
 71 int main() {
 72     ios::sync_with_stdio(false);
 73     #ifndef ONLINE_JUDGE
 74         freopen("data.in", "r", stdin);
 75         freopen("data.out", "w", stdout);
 76     #endif
 77     
 78     __int64 x, y, tmp;
 79     
 80     scanf("%d", &n);
 81     rep(i, 2, n+1)
 82         scanf("%d", &a[i]);
 83     
 84     memset(visit, false, sizeof(visit));
 85     dp[1][1] = -1;
 86     dp[1][0] = 0;
 87     
 88     rep(i, 1, n) {
 89         y = i;
 90         x = i + 1;
 91         tmp = dfs(x, 0);
 92         y = tmp<0 ? -1 : y+tmp;
 93         printf("%I64d\n", y);
 94     }
 95     
 96     #ifndef ONLINE_JUDGE
 97         printf("time = %d.\n", (int)clock());
 98     #endif
 99     
100     return 0;
101 }

 

posted on 2015-07-05 16:48  Bombe  阅读(575)  评论(0编辑  收藏  举报

导航