D. Reachable Strings(想法 哈希hash)

http://codeforces.com/problemset/problem/1320/D

题意:

给一个01串,每次询问两个子串是否可以转换。转换操作为不限次数的011与110互换。

解析:

对于一个串的0序列,再人任意次操作后,0序列的每个0的奇偶性都不会变化。所以可以hash0的奇偶性。

(直接hash[i]=hash[i-1],如果是0再变化会比较方便,不需要lowerbound了)

代码:

/*
 *  Author : Jk_Chen
 *    Date : 2020-03-18-14.54.25
 */
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define uLL unsigned long long
#define rep(i,a,b) for(int i=(int)(a);i<=(int)(b);i++)
#define per(i,a,b) for(int i=(int)(a);i>=(int)(b);i--)
#define mmm(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define pill pair<int, int>
#define fi first
#define se second
#define debug(x) cerr<<#x<<" = "<<x<<'\n'
const LL mod=1e9+7;
const int maxn=2e5+9;
const int inf=0x3f3f3f3f;
LL rd(){ LL ans=0; char last=' ',ch=getchar();
    while(!(ch>='0' && ch<='9'))last=ch,ch=getchar();
    while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
    if(last=='-')ans=-ans; return ans;
}
#define rd rd()
/*_________________________________________________________begin*/
char x[maxn];
LL has[maxn][2];
LL bit[maxn];
int a[maxn],top;
bool odd[maxn];
pair<LL,int> gethas(int l,int r){
    int L=lower_bound(a+1,a+1+top,l)-a;
    if(L>top||a[L]>r)return {0,0};
    int R=upper_bound(a+1,a+1+top,r)-a-1;
    if(l&1){
        return {(has[R][0]-has[L-1][0]*bit[R-L+1]%mod+mod)%mod,R-L+1};
    }
    else{
        return {(has[R][1]-has[L-1][1]*bit[R-L+1]%mod+mod)%mod,R-L+1};
    }
}

int main(){
    int n=rd;
    scanf("%s",x+1);
    rep(i,1,n){
        if(x[i]=='0'){
            a[++top]=i;
            if(i&1)odd[top]=1;
        }
    }
    rep(i,1,top){
        if(odd[i]){
            has[i][0]=(has[i-1][0]*31+1)%mod;
            has[i][1]=(has[i-1][1]*31+2)%mod;
        }
        else{
            has[i][0]=(has[i-1][0]*31+2)%mod;
            has[i][1]=(has[i-1][1]*31+1)%mod;
        }
    }
    bit[0]=1;
    rep(i,1,n)bit[i]=bit[i-1]*31%mod;
    int q=rd;
    while(q--){
        int a=rd,b=rd,l=rd;
        auto h1=gethas(a,a+l-1);
        auto h2=gethas(b,b+l-1);

        if(h1.fi==h2.fi&&h1.se==h2.se){
            puts("Yes");
        }
        else{
            puts("No");
        }
    }
    return 0;
}
/*_________________________________________________________end*/

发布了773 篇原创文章 · 获赞 345 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/jk_chen_acmer/article/details/104947195