Face The Right Way POJ - 3276(区间)
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.
Lines 2.. N+1: Line i+1 contains a single character, F or B, indicating whether cow i is facing forward or backward.
7 B B F B F B BSample Output
3 3Hint
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 using namespace std; 6 const int maxn=5e3+3; 7 int n; 8 char fac; 9 bool face[maxn],f[maxn];//face: 0->qian 1->hou f:0->don't need turn ,1->need 10 int Fan(int len){ 11 memset(f,0,sizeof(f)); 12 int cishu=0,sum=0;//sum->已经turn的次数 cishu->turn的总次数 13 for(int i=1;i+len-1<=n;++i){ 14 if((face[i]+sum)%2==1){//i朝后 15 cishu++; 16 f[i]=1; 17 } 18 sum+=f[i]; 19 if(i-len+1>=1)sum-=f[i-len+1];//现在 sum 是下一个i已经turn的次数了 20 } 21 //因为最后一个i是离最后一头牛len-1长度,检查未处理过的牛是否朝后,if this,无解 22 for(int i=n-len+1+1;i<=n;++i){ 23 if((face[i]+sum)%2==1)return -1; 24 if(i-len+1>=1)sum-=f[i-len+1]; 25 } 26 return cishu; 27 } 28 void Solve(){ 29 int K=n,cishu=n; 30 for(int len=1;len<=n;++len){//枚举区间长度 31 int m=Fan(len); 32 if(m>=0&&cishu>m){ 33 cishu=m;K=len; 34 } 35 } 36 printf("%d %d\n",K,cishu); 37 return; 38 } 39 int main(){ 40 // freopen("1.in","r",stdin); 41 scanf("%d",&n); 42 for(int i=1;i<=n;++i){ 43 scanf(" %c",&fac); 44 if(fac=='B')face[i]=1; 45 } 46 Solve(); 47 return 0; 48 }