http://codeforces.com/contest/284/problem/D
dp+记忆化搜索
代码:
#include<iostream> #include<cmath> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<stack> #include<queue> #include<map> #include<set> #include<algorithm> #define LL long long using namespace std; const int INF=0x3f3f3f3f; const int N=200005; long long inc[N],decr[N]; int had1[N],had2[N]; int a[N]; int n; long long dpdecr(int x,int k); long long dpinc(int x,int k) {//cout<<"inc "<<x<<" "<<k<<endl; if(x<=0||x>n) return 0; if(had1[x]==k) return -1; if(inc[x]!=-2) return inc[x]; had1[x]=k; long long tmp=dpdecr(x+a[x],k); if(tmp==-1) return (inc[x]=-1); return (inc[x]=tmp+a[x]); } long long dpdecr(int x,int k) {//cout<<"decr "<<x<<" "<<k<<endl; if(x<=0||x>n) return 0; if(had2[x]==k) return -1; if(decr[x]!=-2) return decr[x]; had2[x]=k; long long tmp=dpinc(x-a[x],k); if(tmp==-1) return (decr[x]=-1); return (decr[x]=tmp+a[x]); } int main() { //freopen("data.in","r",stdin); while(cin>>n) { for(int i=2;i<=n;++i) cin>>a[i]; memset(had1,0,sizeof(had1)); memset(had2,0,sizeof(had2)); for(int i=1;i<=n;++i) inc[i]=decr[i]=-2; inc[1]=-1; decr[1]=0; for(int i=2;i<=n;++i) { long long k=dpdecr(i,i); if(k==-1) cout<<"-1"<<endl; else cout<<(k+i-1)<<endl; } } return 0; }