易知最后的序列只可能是-1...0....1...
那么直接dp就好。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxn 1000050 #define inf 1000000007 using namespace std; int n,x[maxn],dp[maxn][4]; int main() { scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&x[i]); dp[1][0]=dp[1][1]=dp[1][2]=inf; dp[1][x[1]+1]=0; for (int i=2;i<=n;i++) { dp[i][0]=dp[i-1][0]+x[i]+1; dp[i][1]=(x[i]!=0)*inf+dp[i-1][1]; if (x[i]==0) dp[i][1]=min(dp[i-1][0],dp[i][1]); else if (x[i]==1) dp[i][1]=min(dp[i-1][0]+1,dp[i][1]); dp[i][2]=inf; if (x[i]==-1) dp[i][2]=min(dp[i][2],dp[i-1][2]+2); else if (x[i]==0) dp[i][2]=min(dp[i][2],dp[i-1][2]+1); else dp[i][2]=min(dp[i][2],min(dp[i-1][0],min(dp[i-1][1],dp[i-1][2]))); dp[i][0]=min(dp[i][0],inf);dp[i][1]=min(dp[i][1],inf);dp[i][2]=min(dp[i][2],inf); } int ret=min(dp[n][0],min(dp[n][1],dp[n][2])); if (ret>=inf) printf("BRAK\n");else printf("%d\n",ret); return 0; }