开关问题--反转 poj 3276

来源:互联网 发布:手势识别中算法的用途 编辑:程序博客网 时间:2024/06/07 15:45

Face The Right Way
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 5418 Accepted: 2533

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 Kcows, 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

题意:N头牛排成了一列。每头牛或者向前或者向后,为了让所有的牛都面向前,农夫买了以台自动转向的机器,只有个机器在购买时就必须设定一个数值K,机器每次操作一次

恰好使K头牛连续的牛转向,请求出为了让所有的牛都转成面向前方需要的最少次的操作次数M和对应的最小的K。


例子:   N=7   BBFBFBB   (F:前面   B:后面)    (红色的为要反转的)   此出K=3  M=3  

B B F B F B B

F F B B F B B

F F F F B B B

F F F F F F F   成功了


如果用暴力的方法的话:   考虑N头牛的话最坏情况下要进行N-k+1次反转操作。

for(k=1;k<=N;k++)

for(i=1;i<=N;i++)

for(j=i;j<=i+k;j++)

因此复杂度为n^3  。

在这里我们可以将反转操作给优化了,最后成n^2;


344ms:


calc确定区间还没有看懂 ,先留着之后看。



#include<iostream>#include<string.h>#include<string>using namespace std;int n;int  dir[5005];int f[5005];// 区间[i,i+k-1]是否进行了反转int calc(int k){memset(f,0,sizeof(f));int res=0;int sum=0;  //f的和for(int i=0;i+k<=n;i++){if((dir[i]+sum)%2!=0)//前端的牛朝后方res++,f[i]=1;sum+=f[i];if(i-k+1>=0)sum-=f[i-k+1];}//检查剩下的牛是否有面朝后方的情况for(int i=n-k+1;i<n;i++){if((dir[i]+sum)&2!=0)return -1;if(i-k+1>=0)sum-=f[i-k+1];}return res;}void solve(){int K=1,M=n;for(int k=1;k<=n;k++){int m=calc(k);//cout<<m<<endl;if(m>=0&&M>m)M=m,K=k;}cout<<K<<" "<<M<<endl;}int main(){char a;scanf("%d",&n);for(int i=0;i<n;i++){getchar();scanf("%c",&a);if(a=='F') dir[i]=0;else dir[i]=1;}solve();return 0;}




原创粉丝点击