Necklace

Analysis: Q is determined only for the first one of the strings long times (corresponding to a chain loop off), and then hashes two strings, the last \ (O (N) \) scan for a length of n the hash value of the string can be the same as for the second question need to use the "minimum representation of the string" temporary blog go to school for a moment, this algorithm is also \ (O (N) \) is.

//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
inline int read(){
    int x=0,o=1;char ch=getchar();
    while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
    if(ch=='-')o=-1,ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*o;
}
const int mod=998244353;
const int N=1000005;
char s[N],s1[N],s2[N];
unsigned long long f1[N*2],f2[N],p1[N*2];
int main(){
    scanf("%s",s1+1);scanf("%s",s2+1);
    int n=strlen(s1+1);
    for(int i=1;i<=n;++i)s1[n+i]=s1[i];
    p1[0]=1;
    for(int i=1;i<=2*n;++i){
        f1[i]=f1[i-1]*131+(s1[i]-'0'+1);
        p1[i]=p1[i-1]*131;
    }
    for(int i=1;i<=n;++i)f2[i]=f2[i-1]*131+(s2[i]-'0'+1);
    int bj=1;
    for(int i=1;i<=n;++i){
        int l=i,r=i+n-1;
        if(f1[r]-f1[l-1]*p1[r-l+1]==f2[n]){
            puts("Yes");bj=0;break;
        }
    }
    if(bj)puts("No");
    else{
        for(int i=0;i<n;++i)s[i]=s1[i+1];
        int i=0,j=1,k=0;
        while(i<n&&j<n&&k<n){
            int t=s[(i+k)%n]-s[(j+k)%n];
            if(!t)++k;
            else{
                if(t>0)i+=k+1;
                else j+=k+1;
                if(i==j)++j;
                k=0;
            }
        }
        int pos=min(i,j)+1;
        for(int i=pos;i<pos+n;++i)cout<<s1[i];
        cout<<endl;
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/PPXppx/p/11248034.html