传送门:http://poj.org/problem?id=3276
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 5468 | Accepted: 2561 |
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
Source
题意:N头牛面朝正面或者反面,每次翻转区间长度为K的区间,翻转M次使得所有牛面朝前
求出求小的K和最小的M
思路:这是一个很基础的简单的开关问题,如果常规思路从最左面枚举依次判断每头牛是否翻和所在翻转长度,需要n^3复杂度,为降低复杂度,存储区间i到i+k-1是否进行了翻转。核心思路是翻转偶数次相当于没有操作,所以主要判断奇偶
代码如下:
#include<iostream>
#include<sstream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#define cl(a,b) memset(a,b,sizeof(a))
#define in freopen("F://1.txt","r",stdin)
#define out freopen("F://2.txt","w",stdout)
using namespace std;
typedef long long ll;
const int mod=10000000007;
const ll inf=(ll)1<<60;
const int maxn=1e5+7;
int n,d[maxn],f[maxn];///表示[i, i+K-1]部分是否进行了反转
int ans(int k)
{
int i, j, t = 0, sum = 0;
cl(f,0);
for(i = 0; i <= n-k; i++)
{
if((d[i] + sum) % 2) ///反转为奇数
{
f[i] = 1;
sum += f[i];
t ++;
}
if(i - k + 1 >= 0)
{
sum -= f[i-k+1];
}
}
for( i = n - k + 1; i < n; i ++)
{
if((d[i] + sum) % 2)
return -1;
if(i-k+1>=0)
sum -= f[i-k+1];
}
return t;
}
int main()
{
int i,j;
char c;
//in;
while(~scanf("%d",&n))
{
for(i = 0 ; i < n; i ++)
{
scanf("\n%c",&c);
if(c == 'F')///记录每头牛的方向
d[i] = 0;
else
d[i] = 1;
}
int ans_m = n, ans_k = 1;
for(i = 1; i <= n; i ++)
{
int m = ans(i);
if(m >= 0 && m < ans_m)
{
ans_m = m;
ans_k = i;
}
}
printf("%d %d\n",ans_k,ans_m);
}
return 0;
}