Description
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
Sample Input
7
B
B
F
B
F
B
B
Sample Output
3 3
题目大意:给你n头牛,只能翻转连续的k头牛,要你求出最小的翻转次数,即最后只有‘F’没有‘B’;
解题思路:首先对于确定的K来讨论,到最后枚举k的全部取值可能性即可;首先采用贪心策略,即遇到'B'就翻转对应的区间,如果一个字符串长度为n,最多只能考虑到n-k+1,因为再往下就超出了n了;再来考虑一下为什么这样贪心是可行的,因为翻转对于最后某种可行的方案来说是独立的,就是说你翻转的区间与次序无关,另外翻转的区间产生的效果只有两种要么不变要么与前面相反。那么就是说这个区间要么转要么不转,当你扫一遍时,以当前点为左端点的区间就当前一个,所以直接能确定是否翻转。
另外就是尺取法,因为当前点是由之前几个点共同作用的结果,所以要记录k长区间内翻转总和sum,用尺取法思想对sum增加或减少。
AC代码:
# include <cstdio>
# include <cstring>
# include <algorithm>
using namespace std;
char s[10010];
int f[10010];
int main(){
int n, k, cur, i, j, sum, Min, ans_l, cnt, flage;
while(scanf("%d", &n)!=EOF){
getchar();
cur=n+1;
for(j=1; j<=n; j++){
s[cur++]=getchar();
getchar();
}
Min=2000000000;
for(k=1; k<=n; k++){
memset(f, 0, sizeof(f));//存储每个点是否被翻转
cnt=0;
sum=0;
for(j=n+1; j<=2*n-k+1; j++){
if(s[j]=='B'&&sum%2==0||s[j]=='F'&&sum%2==1){
cnt++;
sum++;//更新sum
f[j]=1;
}
sum=sum-f[j-k+1];//更新sum
}
flage=0;
for(j=2*n-k+2; j<=2*n; j++){
if(s[j]=='B'&&sum%2==0||s[j]=='F'&&sum%2==1){
flage=1;//后面还有'B'
break;
}
sum=sum-f[j-k+1];
}
if(!flage){//判断后面是否已经全为'F'
if(cnt<Min){
ans_l=k;
Min=cnt;
}
}
}
printf("%d %d\n", ans_l, Min);
}
return 0;
}