https://www.luogu.com.cn/problem/P2882
思路:题目说找k,使得m最小。其中每一个k对应着一个m,我们只需要去枚举k并求出当前k下的m,比较大小更新答案就可以了。
题目中k的范围给出来了,想到了二分,但是并不满足决策单调性,所以改为枚举。
k确定后就要进行翻转操作,我们用0代表牛头朝前,1代表朝后。反转操作使用^。0^1 = 1,1^1 = 0。因为是对区间进行操作,所以想到了差分。
什么时候进行翻转操作呢,我们可以从头开始遍历,当当前的牛朝后时,对从当前牛开始的,区间长度为k的区间进行翻转。
#include<cstdio>
#include<iostream>
#include<vector>
#include<iomanip>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iterator>
using namespace std;
int N;
int num[5005];
char a;
int cnt[5005];
int main()
{
cin >> N;
for (int i = 1; i <= N; i++) {
cin >> a;
if (a == 'B')num[i] = 1;
if (a == 'F')num[i] = 0;
}
int ans = 50000;
int tj = 0;
for (int j = N; j >= 1; j--) { //枚举k长度
int c = 0;
int t = 0;
int flag = 1;
fill(cnt, cnt + 5005, 0); //差分数组
for (int i = 1; i <= N; i++) {
t ^= cnt[i]; //t为当前牛翻转的次数,偶数次为0,奇数次为1
if ((num[i] ^ t) == 1) { //当前牛的朝向为朝后
if (i + j - 1 > N) {
flag = 0;
break;
}
c++;
//区间修改,当前牛已经面朝前了,所以直接从后面牛开始进行翻转
cnt[i+1] ^= 1;
cnt[i+j] ^= 1;
}
}
if (flag) {
if (ans > c) {
ans = c;
tj = j;
}
}
}
cout << tj <<" "<<ans<< endl;
return 0;
}