Face The Right Way POJ - 3276 (开关问题)
time limit: 2000ms | memory limit: 65536k | |
total submissions: 6707 | accepted: 3123 |
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
lines 2..n+1: line i+1 contains a single character, f or b, indicating whether cow i is facing forward or backward.
output
sample input
7 b b f b f b b
sample output
3 3
hint
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<cmath> #include<cstdlib> #include<queue> #include<set> #include<map> #include<vector> using namespace std; #define inf 0x3f3f3f3f #define eps 1e-10 typedef long long ll; const int maxn = 5e3+3; const int mod = 1e9 + 7; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int n,m; int dir[maxn],f[maxn]; //牛的方向 f:0 b:1 int calc(int k) { memset(f,0,sizeof(f)); int res=0,sum=0; 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; int m=n; for(int k=1;k<=n;k++) { int m=calc(k); if(m>=0 && m>m) { m=m; k=k; } } cout<<k<<" "<<m<<endl; } int main() { scanf("%d",&n); int num=0; for(int i=0;i<n;i++){ char ch; cin>>ch; if(ch=='b') dir[num]=1; else dir[num]=0; // cout<<dir[num]<<" "; num++; } solve(); return 0; }