题解:P13885 [蓝桥杯 2023 省 Java/Python A] 反异或 01 串
longyitongxue · · 题解
前置知识:Manacher。
此题就是让我们将一个空
-
反异或后的字符串是回文的。
假设有两个待异或的串
a,b ,其中a=rev\left(b\right) 。\$\therefore \forall i\left(1\le i\le \left|a\right|\right),a_i\oplus b_i=a_{\left|a\right|-i+1}\oplus b_{\left|b\right|-i+1}$。\ $\therefore\;$反异或后的字符串是回文的。 -
反异或后的字符串的中心字符为
0 。- 若
01 串长度为偶数,不存在中心字符。 - 若
01 串长度为奇数,设这个01 串为c ,rev\left(c\right) 为d ,不难发现,一个奇数长度的01 串翻转以后中心字符不会变,即c_{\left\lceil\frac{\left|c\right|}{2}\right\rceil}=d_{\left\lceil\frac{\left|d\right|}{2}\right\rceil} ,由于两个相等的数异或结果为0 ,那么反异或后的字符串的中心字符为0 。
- 若
基于上述结论,最少添加
我们跑一遍 Manacher,找到所有以
::::success[Code]{open}
#include<bits/stdc++.h>
using namespace std;
int p[int(2e6+5)],l[int(2e6+5)],mid,r,len;
string s;
void manacher(string x){
s="!$";
for(auto it:x){
s.push_back(it);
s.push_back('$');
}
len=s.size()-1;
for(int i=1;i<=len;i++){
l[i]=l[i-1]+(s[i]=='1');
}
mid=0,r=0;
for(int i=1;i<=len;i++){
if(i>r)p[i]=1;
else p[i]=min(p[2*mid-i], r-i+1);
while(i-p[i]>=1&&i+p[i]<=len&&s[i-p[i]]==s[i+p[i]])p[i]++;
if(i+p[i]-1>r)mid=i,r=i+p[i]-1;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
string t;
cin>>t;
manacher(t);
int ans=2147483647;
for(int i=1;i<=len;i++){
if(s[i]=='1')continue;
ans=min(ans,l[len]-(l[i+p[i]-1]-l[i]));
}
cout<<ans;
return 0;
}
::::
::::align{right}
by