CodeForces 283B Cow Program :给定数组2-n的值,每次变化1的值,按照向佐向右轮流方向走,对于每次变化输出走出数组时走的路长 :记忆化dfs

对于2-n每个点记录向左向右走完接下来要走的路长

为什么可以搜?因为只变化第一个而每次又从第一个走,那我们显然只需要记录每个点向左向右两种值

要记得每次搜索都要初始1节点向右为没走过==

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<algorithm>
 4 using namespace std;
 5 #define LL long long
 6 LL dp[200005][2],a[200005],n;
 7 LL dfs(LL x,LL d)
 8 {
 9   LL tmp;
10   if (x<=0||x>n) return 0;
11   if (dp[x][d]!=0) return dp[x][d];
12   dp[x][d]=-1;
13   if (d) tmp=dfs(x+a[x],0);
14   else tmp=dfs(x-a[x],1);
15   if (tmp==-1) return -1;
16   return dp[x][d]=a[x]+tmp;
17 }
18 int main()
19 {
20   LL i;
21   scanf("%I64d",&n);
22   for (i=2;i<=n;i++) scanf("%I64d",&a[i]);
23   memset(dp,0,sizeof(dp));
24   for (i=1;i<n;i++){
25     a[1]=i; dp[1][1]=0;
26        printf("%I64d\n",dfs(1,1));
27   }
28   return 0;
29 }
View Code

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

 

posted on 2015-03-28 01:23  xiao_xin  阅读(214)  评论(0编辑  收藏  举报

导航