Face the right way(反转问题,思维题)
Farmer John has arranged his N (1 ≤ N ≤ 5,000) cows in a row and many of them are facing forward, like good cows. Some of them are facing backward, though, and he needs them all to face forward to make his life perfect.
Fortunately, FJ recently bought an automatic cow turning machine. Since he purchased the discount model, it must be irrevocably preset to turn K (1 ≤ K ≤ N) cows at once, and it can only turn cows that are all standing next to each other in line. Each time the machine is used, it reverses the facing direction of a contiguous group of K cows in the line (one cannot use it on fewer than K cows, e.g., at the either end of the line of cows). Each cow remains in the same location as before, but ends up facing the opposite direction. A cow that starts out facing forward will be turned backward by the machine and vice-versa.
Because FJ must pick a single, never-changing value of K, please help him determine the minimum value of K that minimizes the number of operations required by the machine to make all the cows face forward. Also determine M, the minimum number of machine operations required to get all the cows facing forward using that value of K.
Input
Line 1: A single integer: N
Lines 2… N+1: Line i+1 contains a single character, F or B, indicating whether cow i is facing forward or backward.
Output
Line 1: Two space-separated integers: K and M
Example input
7
B
B
F
B
F
B
B
Example output
3 3
译成人话:
有n头奶牛排成一排,有的朝前有的朝后,现在你可以使k(每次翻转必须是k头)头奶牛一次性翻转朝向(n>=k>=1),问你最少的翻转次数和此时对应的k值。
题目要求我们找到最优的k值,也就是区间长度,我们可以从小到大枚举这个k,这稍微有点区间DP的味道,但并不是一码事,对于反转来讲,如果反转的次数为奇数,那么这个区间的牛算是被扭了,但如果次数为偶数,就相当于没动,我们可以依此对1~n-len+1(len就是k)进行遍历,我们每枚举一个点,这个点就可以看成一个len区间的最左端,如果这个牛是反的,我们就把后面的区间都扭一下
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=5000+10;
int n,f[maxn];//若f[i]为1,则说明从i到i+len-1都被扭了
char cow[maxn];
int solve(int len){
memset(f,0,sizeof(f));
int ans=0;//记录反转的次数
int sum=0;//记录区间中牛被反转的次数
for(int i=1;i<=n-len+1;i++){
if(sum%2==0&&cow[i]=='B')//因为反转次数是偶数,所以牛都相当于没变,为了把i扭过来,次数要加1
f[i]=1,ans++;
else if(sum%2==1&&cow[i]=='F')//因为反转次数是奇数,而且牛i朝前
f[i]=1,ans++;
sum+=f[i];
if(i-len+1>=1) sum-=f[i-len+1];//当一个len区间被扭完,为了避免后面不该标记的被标记,把前面的减去
}
for(int i=n-len+2;i<=n;i++){
if(sum%2==0&&cow[i]=='B') return -1;//不满足则返回-1
else if(sum%2==1&&cow[i]=='F') return -1;
sum+=f[i];
if(i-len+1>=1) sum-=f[i-len+1];
}
return ans;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)
scanf(" %c",&cow[i]);
int k=0x3f3f3f3f,minn=0x3f3f3f3f;
for(int i=1;i<=n;i++){
int p=solve(i);
if(p>=0&&p<minn){
minn=p,k=i;
}
}
cout<<k<<" "<<minn<<endl;
return 0;
}