POJ 3276 Face The Right Way

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

Hint

For K = 3, the machine must be operated three times: turn cows (1,2,3), (3,4,5), and finally (5,6,7)
 
题解:
可以发现如果第一个为B那么就必须翻转,同样第一个翻转完以后第二个如果为B那么也必须翻转.
而且同一个区间修改两次是无意义的
于是我们可以一直这样处理下去 就可以得到最小答案
但是不能一个一个改,需要优化,F[i]表示i到i+k-1是否被翻转过, 然后不断记录i到i-k+1的和sum,然后判断sum的奇偶就可以判断这个位置为B还是F
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring> 
 4 #include<cmath>
 5 #include<algorithm>
 6 using namespace std;
 7 const int N=5005;
 8 bool a[N],f[N];int n;
 9 int work(int k)
10 {
11     memset(f,0,sizeof(f));
12     int tmp=0,sum=0;
13     for(int i=1;i<=n-k+1;i++)
14     {
15         if((a[i]+sum)%2)
16         {
17             tmp++;
18             f[i]=true;
19             sum+=f[i];
20         }
21         if(i-k+1>0)sum-=f[i-k+1];
22     }
23     for(int i=n-k+2;i<=n;i++)
24     {
25         if((a[i]+sum)%2)return -1;
26         if(i-k+1>0)sum-=f[i-k+1];
27     }
28     return tmp;
29 }
30 int main()
31 {
32     int ansk=2e8,ansm=2e8;
33     char s[2];
34     scanf("%d",&n);
35     for(int i=1;i<=n;i++)
36     {
37         scanf("%s",s);
38         if(s[0]=='B')a[i]=true;
39     }
40     int t;
41     for(int k=1;k<=n;k++)
42     {
43         t=work(k);
44         if(t!=-1 && t<ansm)ansm=t,ansk=k;
45     }
46     printf("%d %d",ansk,ansm);
47     return 0;
48 }
原文地址:https://www.cnblogs.com/Yuzao/p/7100971.html