【BZOJ】1704: [Usaco2007 Mar]Face The Right Way 自动转身机

【题意】n头牛,一些向前一些向后,每次可以使连续k头牛转身,求使旋转次数最小的k。

【算法】贪心

【题解】这题题解很迷,大概思想是k没有单调性,故枚举k,从左到右扫描遇到一只向后的牛就旋转一次。

贪心正确性易证:旋转前面已经好的显然不可能更优,故往后旋转。

然后还有结尾不足k头牛算错……为什么?不知道。

实际数据好像k是有单调性的,可能数据太水。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=5010;

bool a[maxn],b[maxn];
int cnt,n,ans;
char s[10];
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%s",s);
        if(s[0]=='F')a[i]=0;else a[i]=1;
    }
    for(int k=n;k>=1;k--){
        bool ok=1;
        int p=0;cnt=0;
        for(int i=1;i<=n;i++)b[i]=0;
        for(int i=1;i<=n;i++){
            p^=b[i];
            if(p^a[i]){
                if(i+k-1>n){ok=0;break;}
                p^=1;b[i+k]^=1;cnt++;
            }
        }
        if(ok){ans=k;break;}
    }
    printf("%d %d",ans,cnt);
    return 0;
}
View Code

 

posted @ 2017-09-27 19:47  ONION_CYC  阅读(352)  评论(0编辑  收藏  举报