题解:P15294 [ROI 2012 Day 1] password 密码

· · 题解

本题不难,要求找出字符串 A 中哪个连续子段被替换为其数字和得到了字符串 B。由于数字和最多 6 位,可以枚举 B 中所有长度不超过 6 的连续段作为可能的和。

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
char a[N],b[N];
int n,m;
unsigned long long h1[N],h2[N],p[N];
const int base=131;

unsigned long long get(unsigned long long *h,int l,int r){
    return h[r]-h[l-1]*p[r-l+1];
}

int main(){
    scanf("%s%s",a+1,b+1);
    n=strlen(a+1),m=strlen(b+1);
    p[0]=1;
    for(int i=1;i<=max(n,m);i++)p[i]=p[i-1]*base;
    for(int i=1;i<=n;i++)h1[i]=h1[i-1]*base+a[i];
    for(int i=1;i<=m;i++)h2[i]=h2[i-1]*base+b[i];

    for(int i=1;i<=m;i++){
        for(int len=1;len<=6&&i+len-1<=m;len++){
            if(len>1&&b[i]=='0')continue;
            int sum=0;
            for(int k=0;k<len;k++)sum=sum*10+(b[i+k]-'0');
            int suf=m-(i+len-1);
            int r=n-suf;
            if(i-1>r)continue;// 中间段非空
            if(i-1>0&&get(h1,1,i-1)!=get(h2,1,i-1))continue;
            if(suf>0&&get(h1,r+1,n)!=get(h2,i+len,m))continue;
            int cur=0;
            for(int j=i;j<=r;j++)cur+=a[j]-'0';
            if(cur==sum){
                printf("%d %d\n",i,r);
                return 0;
            }
        }
    }
    return 0;
}