898F - Restoring the Expression
思路:字符串hash,base是10,事实证明对2e64取模会T(也许ull很费时),对1e9+7取模。
代码:
#include<bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define ull unsigned long long #define mem(a,b) memset(a,b,sizeof(a)) const int N=1e6+5; const int base=10; const int MOD=1e9+7; ll h[N]; ll p[N]; int num[N]; string s; void init(string s) { int l=s.size(); h[0]=0; for(int i=0;i<l;i++) { h[i+1]=(h[i]*base+s[i]-'0')%MOD; } p[0]=1; for(int i=1;i<=l;i++)p[i]=(p[i-1]*base)%MOD; } ll get(int l,int r) { if(r-l+1<=0||l-1<0||r<0)return 0; return ((h[r]-h[l-1]*p[r-l+1])%MOD+MOD)%MOD; } bool is(int l,int r) { if(l<0||r>=s.size()-1||l>=r)return false; if((r-l>=2&&s[l+1]=='0')||(s.size()>=r+3&&s[r+1]=='0'))return false; mem(num,0); string s1=s.substr(0,l+1); string s2=s.substr(l+1,r-l); string s3=s.substr(r+1,s.size()-r-1); //cout<<s1<<' '<<s2<<' '<<s3<<endl; if(s2.size()>s3.size()||s1.size()>s3.size())return false; if(s1.size()<s2.size())swap(s1,s2); int tot=1; for(int i=s3.size()-1;i>=0;i--) { if(tot<=s2.size()) { int t=s1[s1.size()-tot]-'0'+s2[s2.size()-tot]-'0'+num[i]; if(t>=10) { if(i==0)return false; num[i-1]=t/10; num[i]=t=t%10; } if(t!=s3[i]-'0')return false; } else if(tot<=s1.size()) { int t=s1[s1.size()-tot]-'0'+num[i]; if(t>=10) { if(i==0)return false; num[i-1]=t/10; num[i]=t=t%10; } if(t!=s3[i]-'0')return false; } else { if(num[i]>=10) { if(i==0)return false; num[i-1]=num[i]/10; num[i]=num[i]%10; } if(num[i]!=s3[i]-'0')return false; } tot++; } return true; } void solve(string s) { init(s); int pos=0,_pos=0; int l=s.size(); for(int i=l-1;i>=0;i--) { int t=l-i; ll sumh=get(i+1,l); if((get(1,t)+get(t+1,i))%MOD==sumh){ pos=t-1; _pos=i-1; if(is(pos,_pos))break; else pos=_pos=0; } if((get(1,t-1)+get(t,i))%MOD==sumh){ pos=t-2; _pos=i-1; if(is(pos,_pos))break; else pos=_pos=0; } if((get(1,i-t)+get(i-t+1,i))%MOD==sumh){ pos=i-t-1; _pos=i-1; if(is(pos,_pos))break; else pos=_pos=0; } if((get(1,i-t+1)+get(i-t+2,i))%MOD==sumh){ pos=i-t; _pos=i-1; if(is(pos,_pos))break; else pos=_pos=0; } } for(int i=0;i<=pos;i++)putchar(s[i]); putchar('+'); for(int i=pos+1;i<=_pos;i++)putchar(s[i]); putchar('='); for(int i=_pos+1;i<l;i++)putchar(s[i]); puts(""); //cout<<pos<<' '<<_pos<<endl; //cout<<get(1,1)<<' '<<get(2,22)<<' '<<get(23,44)<<endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); cin>>s; solve(s); return 0; }