BZOJ3427 Poi2013 Bytecomputer 【dp】
题目链接
题解
容易发现最终序列一定是\(\{-1,0,1\}\)组成的
因为如果有一个位置不是,那么这个位置一定大于\(1\),那么上一个位置一定为\(1\),所以该位置一定加到过\(1\)。由于\(1\)已经满足条件,而经分析得大于\(1\)会使下一个位置的决策不优反劣,所以一定不会大于\(1\)
那么就可以\(dp\)了,设\(f[i][3]\)表示以\(i\)结尾\(i\)为三种数时的最优答案
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 1000005,maxm = 100005,INF = 1000000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int f[maxn][3],n,x[maxn];
int main(){
n = read();
REP(i,n) x[i] = read();
for (int i = 0; i <= 2; i++)
if (i != x[1] + 1) f[1][i] = INF;
else f[1][i] = 0;
for (int i = 2; i <= n; i++){
if (x[i] == -1){
f[i][0] = f[i - 1][0];
f[i][1] = INF;
f[i][2] = f[i - 1][2] + 2;
}
else if (!x[i]){
f[i][0] = f[i - 1][0] + 1;
f[i][1] = min(f[i - 1][0],f[i - 1][1]);
f[i][2] = f[i - 1][2] + 1;
}
else {
f[i][0] = f[i - 1][0] + 2;
f[i][1] = f[i - 1][0] + 1;
f[i][2] = min(f[i - 1][0],min(f[i - 1][1],f[i - 1][2]));
}
}
int ans = min(f[n][0],min(f[n][1],f[n][2]));
if (ans >= INF) puts("BRAK");
else printf("%d\n",ans);
return 0;
}