http://poj.org/problem?id=3661

二维DP

#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdio>

using namespace std;

const int N=10005;
const int M=505;
int L[N];
int rest[N][M];
int norest[N][M];
int main()
{
    int n,m;
    while(scanf("%d %d",&n,&m)!=EOF)
    {
        for(int i=1;i<=n;++i)
        {
            scanf("%d",&L[i]);
        }
        memset(rest,-1,sizeof(rest));
        memset(norest,-1,sizeof(norest));
        rest[1][0]=0;
        norest[1][1]=L[1];
        for(int i=1;i<n;++i)
        {
            for(int j=0;j<=m;++j)
            {
                if(rest[i][j]!=-1)
                {
                    if(j>0)
                    rest[i+1][j-1]=max(rest[i][j],rest[i+1][j-1]);
                    else
                    {
                        rest[i+1][0]=max(rest[i][j],rest[i+1][0]);
                        norest[i+1][1]=max(norest[i+1][1],L[i+1]+rest[i][j]);
                    }
                }
                if(norest[i][j]!=-1)
                {
                    if(j==m)
                    rest[i+1][m-1]=max(rest[i+1][m-1],norest[i][j]);
                    else
                    {
                        int l=max(j-1,0);
                        rest[i+1][l]=max(rest[i+1][l],norest[i][j]);
                        norest[i+1][j+1]=max(norest[i+1][j+1],L[i+1]+norest[i][j]);
                    }

                }
            }
        }
        int MAX=0;
        MAX=max(rest[n][0],MAX);
        MAX=max(norest[n][0],MAX);
        printf("%d\n",MAX);
    }
    return 0;
}
posted on 2012-05-05 20:16  夜->  阅读(129)  评论(0编辑  收藏  举报