首页 > 代码库 > Face The Right Way

Face The Right Way

                            Face The Right Way
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 2564 Accepted: 1177

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

7BBFBFBB

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)
 1 #include"iostream" 2 #include"cstring" 3 #include"cstdio" 4 #include"algorithm" 5 #include"cstdlib" 6 #include"ctime" 7 using namespace std; 8 const int ms=5001; 9 int dir[ms];10 int f[ms];11 int N;12 int calc(int K)13 {14     memset(f,0,sizeof(f));15     int res=0;16     int sum=0;//f的∑17     for(int i=0;i+K<=N;i++)18     {19         if((dir[i]+sum)&1)20         {21             res++;22             f[i]=1;23         }24         sum+=f[i];25         if(i-K+1>=0)26         {27             sum-=f[i-K+1];28         } 29     } 30     for(int i=N-K+1;i<N;i++)31     {32         if((dir[i]+sum)&1)33             return -1;34         if((i-K+1)>=0)35             sum-=f[i-K+1];36     }37     return res;38 }39 void solve()40 {41     int K=1,M=N;42     for(int k=1;k<=N;k++)43     {44         int m=calc(k);45         if(m>=0&&M>m)46         {47             M=m;48             K=k;49         }50     }51     printf("%d %d\n",K,M);52 }53 int main()54 {55     scanf("%d",&N);56     char str[5]; 57     for(int i=0;i<N;i++)58     {59         scanf("%s",str);60         if(str[0]==B)61             dir[i]=1;62         else63             dir[i]=0;64     }65     solve();66     return 0;67 }

 

 

Face The Right Way