Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 2899 | Accepted: 1338 |
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
Lines 2..N+1: Line i+1 contains a single character, F or B, indicating whether cow i is facing forward or backward.
Output
Sample Input
7 B B F B F B B
Sample Output
3 3
Hint
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <string> 7 #include <vector> 8 #include <set> 9 #include <map> 10 #include <queue> 11 #include <stack> 12 #include <sstream> 13 #include <iomanip> 14 using namespace std; 15 const int INF=0x4fffffff; 16 const int EXP=1e-6; 17 const int MS=5005; 18 19 int dir[MS]; 20 int flag[MS]; // [i->i+k-1] 这个区间是否翻转。 21 int N; 22 23 int calc(int k) 24 { 25 int sum=0,res=0; 26 memset(flag,0,sizeof(flag)); 27 for(int i=0;i+k-1<N;i++) 28 { 29 if((dir[i]+sum)&1) 30 { 31 flag[i]=1; 32 res++; 33 } 34 sum+=flag[i]; 35 if(i-k+1>=0) 36 sum-=flag[i-k+1]; 37 } 38 // N-k+1 --> N-1 这个区间的任意一个位置起无法翻转。 39 // 需要检查这段区间是不是全部朝前。 40 for(int i=N-k+1;i<N;i++) 41 { 42 if((dir[i]+sum)&1) 43 return -1; 44 if(i-k+1>=0) 45 sum-=flag[i-k+1]; 46 } 47 return res; 48 } 49 50 51 void solve() 52 { 53 int K=1,M=N; 54 for(int k=1;k<=N;k++) 55 { 56 int cnt=calc(k); 57 if(cnt>=0&&M>cnt) 58 { 59 M=cnt; 60 K=k; 61 } 62 } 63 printf("%d %d ",K,M); 64 } 65 66 int main() 67 { 68 char s[5]; 69 scanf("%d",&N); 70 for(int i=0;i<N;i++) 71 { 72 scanf("%s",s); 73 if(s[0]=='F') 74 dir[i]=0; 75 else 76 dir[i]=1; 77 } 78 solve(); 79 return 0; 80 }