Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 4081 | Accepted: 1868 |
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
题意:
N头牛排成了一列。每头牛或者向前或者向右。为了让所有的牛都面向前方,农夫约翰买了一台自动转向的机器。这个机器在购买时就必须设定一个数值K,机器每操作一次恰好使K头连续的牛转向。请求出为了让所有的牛都能面向前方需要的最少的操作次数M和对应的最小的K。
分析:
首先,交换区间反转的顺序对结果是没有影响的。此外,可以知道对同一个区间进行两次以上的反转是多余的,由此,问题就转化成了求需要被反转的区间的集合。于是我们先考虑一下最左端的牛。包含这头牛的区间只有一个,因此如果这头牛面朝前方,我们就能知道这个区间不需要反转。
反之,如果这头牛面朝后方,对应的区间就必须进行反转了。而且在此之后这个最左的区间就再也不需要考虑了。这样一来,通过首先考虑最左端的牛,问题的规模就缩小了1.不断的重复下去,就可以无需搜索求出最少所需的反转次数了。
思路很简单就是从头开始遍历,用数组优化的思想很巧妙,避免了模拟的复杂
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
const int N = 5500;
int dir[N], f[N];
int judge(int k);
int n;
int main()
{
while(scanf("%d", &n)!=EOF)
{
char ch;
for(int i=0;i<n;i++)
{
scanf(" %c", &ch);
if(ch=='B')
{
dir[i]=1;
}
else
{
dir[i]=0;
}
}
int dis, m, num=n;
for(int k=1;k<=n;k++)
{
if(judge(k)>=0)
{
dis=judge(k);
if(dis<num)
{
num=dis;
m=k;
}
}
}
printf("%d %d\n", m, num);
}
return 0;
}
int judge(int k)
{
memset(f,0,sizeof(f));
int sum=0, res=0;
for(int i=0;i+k<=n;i++)
{
if((sum+dir[i])%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;
}