Codeforces Flipping game 动态规划基础

July 19, 2013
CodeForces DP

题目链接:http://codeforces.com/problemset/problem/327/A 这道题目有O(N^3)的做法,这里转化为动态规划求解,复杂度是O(N)


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <queue>
#include <set>
#include <queue>
#include <list>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
int a[102], b[102], c[102];
int main ( void )
{
    int n, n1=0, cnt=0; 
    while (~scanf("%d", &n))
    {
        n1 = cnt = 0;
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        for (int i=1; i<=n; ++i){
            scanf("%d",a+i); if(a[i]) n1++;
            if (a[i]) b[i]=-1; else b[i]=1;
        }
        c[0] = 0;
        for (int i = 1; i <= n; ++i)
        {
            c[i] = c[i-1] + b[i];
        }
        int Max = -INF, Min = c[0];
        for (int i = 1; i <= n; ++i) {
            if (c[i] - Min > Max) Max = c[i]-Min;
            if (c[i] < Min) Min = c[i];
        }
        printf("%d\n",n1+Max);
    }
        return 0;
}            

转化为子序列的最大连续和

comments powered by Disqus