POJ 3276 Face The Right Way (开关问题的优化_好题)

来源:互联网 发布:淘宝自动浏览软件app 编辑:程序博客网 时间:2024/06/08 02:10

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)




注意输入格式!!!!很关键


#include<iostream>#include<cstdio>#include<cstring>using namespace std;int f[5555],a[5555],n;int work(int k)            //开关翻转问题。。区间为k,进行翻转{int i,sum,res;sum=res=0;memset(f,0,sizeof(f));for(i=0;i+k<=n;i++) {if((a[i]+sum)%2) {res++;f[i]=1;}sum+=f[i];if(i-k+1>=0) sum-=f[i-k+1];}for(i=n-k+1;i<n;i++) {if((a[i]+sum)%2) return -1;if(i-k+1>=0) sum-=f[i-k+1];}return res;}int main(){int i,j;int k,M;char ch;scanf("%d",&n);M=n;k=1;for(i=0;i<n;i++) {getchar();scanf("%c",&ch);if(ch=='F') a[i]=0;else a[i]=1;}for(i=1;i<=n;i++) {int m=work(i);if(m>=0 && m<M) {M=m;k=i;}}printf("%d %d\n",k,M);return 0;}





0 0
原创粉丝点击