T4 P1503 鬼子进村
给定一条链,若干点被断,求给出点所在连通块的大小。 需要找到给出点所在连通块的左右界,则可以用map存储被断的点,则点被自动排序,则可以二分查询第一个大于等于给出点位置的点的位置,再找到前一个被断的点的位置,相减再减一就是答案。 特判:若给出点与二分查询到的点位置一样,即给出点被断,输出0。
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
map<int,int>mp;
stack<int>st;
mp[0]++;mp[n+1]++;
for(int i=1;i<=m;i++){
char op;
cin>>op;
if(op=='D'){
int x;
cin>>x;
mp[x]++;
st.push(x);
}else if(op=='R'){
mp.erase(st.top());
st.pop();
}else{
int x;
cin>>x;
int r=mp.lower_bound(x)->first;
if(x==r){
cout<<0<<endl;
continue;
}
int l=(--mp.lower_bound(x))->first;
cout<<r-l-1<<endl;
}
}
return 0;
}T5 P4391 无线传输
设最小循环串为t,则原串s可以表示为t+t+…+t的部分前缀,可以发现去掉一个t后就是s的公共前后缀,而t内部没有更小的对于s的循环单位,所以可得此公共前后缀为s的最大公共前后缀,结合KMP可得ans=n-b[n]
#include<bits/stdc++.h>
using namespace std;
int b[1000005];
char c[1000005];
int main(){
int n;
cin>>n;
scanf("%s",c+1);
for(int j=0,i=2;i<=n;i++){
while(j&&c[j+1]!=c[i])j=b[j];
if(c[j+1]==c[i])j++;
b[i]=j;
}
cout<<n-b[n];
return 0;
}