题目描述
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、交换区间反转的顺序对结果是没有影响的。
2、对同一个区间进行两次以上的反转是多余的。
我们选定k之后从1到i-k+1依次走一遍,若这个数此时(在原来基础上加上修改次数)朝后,则将以这个数为起点的长度为k的区间进行修改,在修改完之后的操作由于起点都在该点之后,将不会再对该点的状态造成影响。
由于我们要知道该点已经修改几回,则需要维护所有前面已经修改过的且包含该点的次数。我们用一个sum来表示从i-k+1到i-1的修改次数,用ans来存储总的修改次数,即j从i-k+1到i-1的区间和,在走完每一个k值之后,由于sum(i-k+2~i)=sum(i-k+1~i-1)-j[i-k+1]+j[i];我们在跑完一次i要进入下一区间时,我们直接进行
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 const int N=5e3+10; 5 int n,f[N]; 6 char c[N]; 7 int cow(int k){ 8 memset(f,0,sizeof(f)); 9 int ans=0,sum=0; 10 for(int i=1;i<=n-k+1;++i){ 11 if(sum%2==0&&c[i]=='B') 12 f[i]=1,ans++; 13 else if(sum%2==1&&c[i]=='F') 14 f[i]=1,ans++; 15 sum+=f[i]; 16 if(i-k+1>=1) sum-=f[i-k+1]; 17 } 18 for(int i=n-k+2;i<=n;++i){ 19 if(sum%2==0&&c[i]=='B') return -1; 20 else if(sum%2==1&&c[i]=='F') return -1; 21 sum+=f[i]; 22 if(i-k+1>=1) sum-=f[i-k+1]; 23 } 24 return ans; 25 } 26 int main(){ 27 scanf("%d",&n); 28 int m=2147483617,k; 29 for(int i=1;i<=n;++i) scanf(" %c",&c[i]); 30 for(int i=1;i<=n;++i){ 31 int cnt=cow(i); 32 if(cnt>=0&&cnt<m) 33 k=i,m=cnt; 34 } 35 printf("%d %d ",k,m); 36 return 0; 37 }
本文多处借鉴这篇博客https://blog.csdn.net/qq_40889820/article/details/82785549。