参考https://vjudge.net/solution/9596160和http://blog.csdn.net/prolightsfxjh/article/details/76099716
题意:给出字符串A和B,字符串A大小写不区分,字符串B由小写字母构成,构成AB的每种字母的个数相同,询问是否能把B切成3份,重构出字符串A,如果能则输出那三份子串,并按照A的顺序输出。
哈希+枚举
O(n^2)的枚举字符串B 的0~i-1 为第一段,i~j-1 为第二段,j~n-1为第三锻,
然后每次借用这三段的哈希值去和A串匹配,这三段有A(3,3) == 6种排列方式,所以枚举这6种排列,
之后借用它们的哈希值判断能否构造出字符串A。
复杂度 O(n^2)
可是我还是看不太懂这些地方的hash的用法。。。
#include<algorithm>
#include<vector>
#include<cstring>
#include<string>
#include<iomanip>
#include<cstdio>
#include<stack>
#include<iostream>
#include<map>
#include<set>
#include<queue>
#include<cmath>
#include<strstream>
using namespace std;
#define sf scanf
#define pf printf
#define mem(a,b) memset(a,b,sizeof(a));
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define MP make_pair
#define N 1000010
#define M 200020
#define ULL unsigned long long
#define LL long long
#define inf 0x3f3f3f3f
//printf("\n%.2lf sec \n", (double)clock() / CLOCKS_PER_SEC);
const int P=29;
const int maxn=100000;
ULL haha[N],TS[N];
char aa[N],bb[N];
ULL goal;
int n;
void print(char *s,int l,int r){
for(int i=l;i<=r;++i)pf("%c",s[i]);
puts("");
}
int main(){
TS[0]=1;
for(int i=1;i<=maxn;++i)TS[i]=TS[i-1]*P;
sf("%s",aa);
sf("%s",bb);
n=strlen(aa);
if(n<3){puts("NO");return 0;}
for(int i=0;i<n;++i){ goal=goal*P+aa[i]-'a'; }
for(int i=0;i<n;++i){haha[i+1]=haha[i]*P+bb[i]-'a'; }
for(int i=1;i<=n;++i){
for(int k=i+1;k<=n;++k){
ULL ha1=haha[i];
ULL ha2=haha[k]-haha[i]*TS[k-i];
ULL ha3=haha[n]-haha[k]*TS[n-k];
//123
if(ha1*TS[n-i]+ha2*TS[n-k]+ha3==goal){
puts("YES");
print(bb,0,i-1),print(bb,i,k-1),print(bb,k,n-1);
return 0;
}
//132
if(ha1*TS[n-i]+ha3*TS[k-i]+ha2==goal){
puts("YES");
print(bb,0,i-1);print(bb,k,n-1),print(bb,i,k-1);
return 0;
}
//213
if(ha2*TS[n-k+i]+ha1*TS[n-k]+ha3==goal){
puts("YES");
print(bb,i,k-1);print(bb,0,i-1);print(bb,k,n-1);
return 0;
}
//231
if(ha2*TS[n-k+i]+ha3*TS[i]+ha1==goal){
puts("YES");
print(bb,i,k-1),print(bb,k,n-1),print(bb,0,i-1);
return 0;
}
//321
//312
}
}
puts("NO");
}