bzoj1609 [Usaco2008 Feb]Eating Together麻烦的聚餐(dp)

dp[i][1/2/3]表示把前i个变成以1/2/3结尾的合法队列的最少改动数,正着倒着各做一遍取最小。 O(n)

#include 
#include 
#define N 30005
int n,a[N],dp[N][4],ans=0;
inline int min(int x,int y){return xint main(){
//  freopen("a.in","r",stdin);
    scanf("%d",&n);
    for(int i=1;i<=n;++i) scanf("%d",&a[i]);
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=n;++i){
        dp[i][1]=dp[i-1][1]+(a[i]==1?0:1);
        dp[i][2]=min(dp[i-1][2],dp[i-1][1])+(a[i]==2?0:1);
        dp[i][3]=min(min(dp[i-1][2],dp[i-1][1]),dp[i-1][3])+(a[i]==3?0:1);
    }
    ans=min(dp[n][1],min(dp[n][2],dp[n][3]));
    for(int i=n;i>=1;--i){
        dp[i][1]=dp[i+1][1]+(a[i]==1?0:1);
        dp[i][2]=min(dp[i+1][2],dp[i+1][1])+(a[i]==2?0:1);
        dp[i][3]=min(min(dp[i+1][2],dp[i+1][1]),dp[i+1][3])+(a[i]==3?0:1);
    }
    ans=min(min(ans,dp[1][1]),min(dp[1][2],dp[1][3]));
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(bzoj)