• D. Cow Program 夜


    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;
    }
    

      

  • 相关阅读:
    文件处理
    集合 字符编码
    3-11作业
    win 10 在vs2017下对mpi的安装以及认识
    java中二维数组的排序
    java中Arrays的用法
    java中随机二维数组中寻找最大值并输出坐标
    用java打印图形
    面向对象object与constructor
    for each in for in 与for of
  • 原文地址:https://www.cnblogs.com/liulangye/p/2966309.html
Copyright © 2020-2023  润新知