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.
InputLines 2.. N+1: Line i+1 contains a single character, F or B, indicating whether cow i is facing forward or backward.
7 B B F B F B BSample Output
3 3Hint
#include<cstdio>
#include<cstring>
#define inf 0x7fffffff
int n,K,M=inf,dir[5005],f[5005];
//K,M是最后要输出的设定长度和翻转次数,dir是初始方向,f是翻转次数(只有0和1次)
char ch;
int cal(int k)
{
memset(f,0,sizeof(f));
//最开始都是为翻转过
int sum=0,res=0;
//sum是i-k+1到i范围(长度为k)内翻转的次数和,res是总次数和即当前的m
for(int i=0;i+k-1<n;i++)//此过程用样例在纸上写写有助理解
{
if((sum+dir[i])&1)//sum是这一段翻过的次数,dir是本来朝向,如果加和是奇数代表朝后,要翻一次
{
res++;
f[i]=1;
}
//下面是对sum随段移动的更新,加上当前的,减去马上离开的
sum+=f[i];
if(i-k+1>=0)
sum-=f[i-k+1];
}
//对最后几个进行检查
for(int i=n-k+1;i<n;i++)
{
if((sum+dir[i])&1)//还有朝后的,由于要翻只能一段一起翻,这是最后一段已经翻过了,所以无解
return -1;
if(i-k+1>=0)
sum-=f[i-k+1];
}
return res;
}
int main()
{
//输入
scanf("%d",&n);
for(int i=0;i<n;i++)
{
getchar();
ch=getchar();
dir[i]=ch=='F'?0:1;
//将朝前设置为0,将朝后设置为1,主要为了核心部分取模而设置
}
//枚举k
for(int k=1;k<=n;k++)
{
int m=cal(k);//cal函数计算当前k所需m,若为-1则意为无解
if(m>=0&&m<M)//更新所需结果
{
M=m;
K=k;
}
}
//输出
printf("%d %d",K,M);
return 0;
}