URAL 1989(線段樹+字串雜湊)
阿新 • • 發佈:2018-12-09
題意:給一個字串(<=1e5), 進行操作和查詢(<=1e5)。
1)將指定位置的字元改為c
2)詢問l-r的子串,是否是迴文串。
多項式雜湊:
Hash[i] = Hash[i - 1] * x + s[i](其中1 < i <= n,Hash[0] = 0)
一般地,
而對於l - r區間的hash值,則為:
相當於把左邊L的值給減去,hash[l-1]*x^(r-l+1)就是hash[r]的前l部分;也能理解成hash[l-1]向左移了(r-l+1)位;
KeyL=str[ L] +str[L+1]*K + str[L+2]* K^2 +...str[R] * K^(R-L)
KeyR=str[R] +str[R-1]*K + str[R-2]* K^2 +...str[L] * K^(R-L)
只要是迴文串,則KeyL 與 KeyR 會相等,K為某常數。
用線段樹維護每個區間的KeyL 和 KeyR.
#include<bits/stdc++.h> using namespace std; const int maxn = 1e5+9; char str[maxn]; int Pow[maxn]; int N,M; #define ls l,m,rt<<1 #define rs m+1,r,rt<<1|1 #define K 137 #define FOR(i,n) for(long long (i)=1;(i)<=(n);(i)++) #define For(i,n) for(long long (i)=0;(i)<(n);(i)++) struct Node{ int KeyL,KeyR; Node():KeyL(0),KeyR(0){} void init(){KeyL=KeyR=0;} }node[maxn<<2]; void Pushup(int L,int R,int rt){ node[rt].KeyL=node[rt<<1].KeyL+node[rt<<1|1].KeyL*Pow[L]; node[rt].KeyR=node[rt<<1].KeyR*Pow[R]+node[rt<<1|1].KeyR; } void build(int l,int r,int rt){ if(l==r){ node[rt].KeyL=node[rt].KeyR=str[l]; return; } int m=(l+r)>>1; build(ls); build(rs); Pushup(m-l+1,r-m,rt); } void update(int a,char b,int l,int r,int rt){ if(l==r){ node[rt].KeyL=node[rt].KeyR=b; return; } int m=(l+r)>>1; if(a<=m) update(a,b,ls); if(a> m) update(a,b,rs); Pushup(m-l+1,r-m,rt); } Node query(int L,int R,int l,int r,int rt){ if(L <=l && r <=R){ return node[rt]; } Node ANS,ANS1,ANS2;int T=0; int m=(l+r)>>1; if(L <= m) ANS1=query(L,R,ls),T+=1; if(R >m ) ANS2=query(L,R,rs),T+=2; if(T==1){ANS=ANS1;} else if(T==2) {ANS=ANS2;} else if(T==3) { ANS.KeyL=ANS1.KeyL+ANS2.KeyL*Pow[m-max(L,l)+1]; ANS.KeyR=ANS1.KeyR*Pow[min(R,r)-m]+ANS2.KeyR; } return ANS; } int main() { while(~scanf("%s",str+1)) { str[0]='0';N=strlen(str)-1; Pow[0]=1; for(int i = 1; i<=N; i++) Pow[i]=Pow[i-1]*K; for(int i = 0; i<(maxn<<2); i++) node[i].init(); scanf("%d",&M); build(1,N,1); for(int i = 1; i<=M; i++) { char op[20];scanf("%s",op); if(op[0]=='c'){ int a;char b; scanf("%d %c",&a,&b); update(a,b,1,N,1); } else{ int a,b; scanf("%d%d",&a,&b); Node ANS=query(a,b,1,N,1); bool T=ANS.KeyL==ANS.KeyR; if(T) printf("Yes\n"); else printf("No\n"); } } } return 0; }