题目概括
题目描述
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.
$N$头牛排成一列。每头牛或者向前或者向后。为了让所有牛都 面向前方,农夫每次可以将$K$头连续的牛转向,求操作的最少次数$M$和对应的最小$K$。
$B$表示当前奶牛往后看,$F$表示奶牛往前看。
样例输入输出格式
输入格式
Line 1: A single integer: N
Lines 2..N+1: Line i+1 contains a single character, F or B, indicating whether cow i is facing forward or backward.
输出格式
Line 1: Two space-separated integers: K and M
输入输出样例
输入 #1
7
B
B
F
B
F
B
B
输出 #1
3 3
数据范围
样例解释
For K = 3, the machine must be operated three times: turn cows (1,2,3), (3,4,5), and finally (5,6,7)
$$
1 \le N \le 5000 \\\\
1 \le K \le N \\\\
$$
解题报告
题意理解
$N$头牛排成一列。每头牛或者向前或者向后。为了让所有牛都 面向前方,农夫每次可以将$K$头连续的牛转向,求操作的最少次数$M$和对应的最小$K$。
算法解析
这道题目,其实就是一个贪心的题目。
我们知道,因为同一个点翻转两次相当于没有翻转,这就是异或的特性
每个点,只有正反之分,所以这就是01
然后设计贪心,如下所示:
从左到右对于出现的每一个$0$,然后我们就不得不翻转一次,从当前点开始的区间。
但是,我们发现这个贪心,时间复杂度过大
从左到右枚举。$O(n)$
枚举区间长度。$O(n)$
区间翻转。$O(n)$
综上所述,复杂度为$O(n^3)$
我们怎么降维打击时间复杂度呢,我们思考一下。
区间翻转,然后又是类似于区间异或。
我们似乎可以使用,差分,这个支持区间异或的算法。
于是,我们可以通过,差分优化本题目。
代码解析
#include <bits/stdc++.h>
using namespace std;
const int N=5010;
int n,a[N],sum[N],d[N],cnt,ans=1e9,pos,now,ok;
char c;
inline void init()
{
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
getchar();
c=getchar();
c=='B' ? a[i]=0:a[i]=1;//设置
}
}
inline void work()
{
for(int k=1; k<=n; k++)
{
now=0,cnt=0,ok=1;
memset(d,0,sizeof(d));
for(int i=1; i<=n; i++)
{
now^=d[i];//异或
if(!a[i]^now)//是时候要异或了,发现了反方向的奶牛
{
if(i+k-1>n)//不能超过最大长度
{
ok=false;
break;
}
now^=1;//异或
d[i+k]^=1;//同时在区间右端点异或,保证最后没有问题
cnt++;
}
}
if(ok && ans>cnt)//记得更新答案哦
ans=cnt,pos=k;
}
printf("%d %d\n",pos,ans);
}
int main()
{
init();
work();
return 0;
}