CF 1955 E. Long Inversions (*1700) 贪心 差分
CF 1955 E. Long Inversions (*1700) 贪心 差分
题意:
给你一个长度为 \(n\) 的二进制字符串,你可以选择一个整数 \(k\) ,然后可以选择连续的 \(k\) 个字符进行反转。如果能够操作任意次将字符串变成全 \(1\) 字符串。那么这个 \(k\) 就是合法的。求出最大合法的 \(k\) 值。 \(n \le 5000\)。
思路:
看到数据范围,想到暴力枚举 \(k\) ,然后 \(check\) 即可。贪心就是对于每个 \(0\) 的位置,我们都需要对齐长度为 \(k\) 的子区间进行操作,最后判断结尾 \(k-1\) 个字符是否含 \(0\) 即可。维护区间反转次数,可以用线段树或树状数组。这里我们可以利用异或的性质,进行差分。更加方便。时间复杂度 \(0(n^2)。\)
代码:
#include<bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define all(u) u.begin(), u.end()
#define endl '\n'
#define debug(x) cout<<#x<<":"<<x<<endl;
typedef pair<int, int> PII;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 1e5 + 10, M = 105;
const int mod = 1e9 + 7;
const int cases = 1;
void Showball(){
int n;
cin>>n;
string s;
cin>>s;
s="?"+s;
auto check=[&](int k){
vector<int> f(n+2);
for(int i=1;i<=n-k+1;i++){
int c=s[i]-'0';
f[i]^=f[i-1];
c^=f[i];
if(!c) f[i]^=1,f[i+k]^=1;
}
for(int i=n-k+2;i<=n;i++){
int c=s[i]-'0';
f[i]^=f[i-1];
c^=f[i];
if(!c) return false;
}
return true;
};
for(int i=n;i>=1;i--){
if(check(i)) return cout<<i<<endl,void();
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T=1;
if(cases) cin>>T;
while(T--)
Showball();
return 0;
}

浙公网安备 33010602011771号