题目链接:http://icpc.njust.edu.cn/Problem/Pku/3461/
代码如下:
1 #include<cstdio> 2 #include<string.h> 3 using namespace std; 4 typedef unsigned int ui; 5 typedef long long ll; 6 typedef unsigned long long ull; 7 #define pf printf 8 #define mem(a,b) memset(a,b,sizeof(a)) 9 #define prime1 1e9+7 10 #define prime2 1e9+9 11 #define pi 3.14159265 12 #define lson l,mid,rt<<1 13 #define rson mid+1,r,rt<<1|1 14 #define scand(x) scanf("%llf",&x) 15 #define f(i,a,b) for(int i=a;i<=b;i++) 16 #define scan(a) scanf("%d",&a) 17 #define dbg(args) cout<<#args<<":"<<args<<endl; 18 #define inf 0x3f3f3f3f 19 #define maxn 1000010 20 int n,m,t; 21 ull Hash[maxn],h[maxn]; 22 char a[maxn],b[maxn]; 23 const int p=131; 24 void init() 25 { 26 h[0]=1; 27 f(i,1,maxn-1) 28 { 29 h[i]=h[i-1]*p; 30 } 31 } 32 33 int main() 34 { 35 //freopen("input.txt","r",stdin); 36 //freopen("output.txt","w",stdout); 37 //std::ios::sync_with_stdio(false); 38 scan(t); 39 init(); 40 while(t--) 41 { 42 scanf("%s%s",&a,&b); 43 int lena=strlen(a); 44 int lenb=strlen(b); 45 int ans=0; 46 int hasha=a[0]-'a',hashb; 47 f(i,1,lena-1) 48 { 49 hasha=hasha*p+a[i]-'a'; 50 } 51 Hash[0]=b[0]-'a'; 52 f(i,1,lenb-1) 53 { 54 Hash[i]=Hash[i-1]*p+b[i]-'a'; 55 } 56 f(i,0,lenb-lena) 57 { 58 int l=i; 59 int r=l+lena-1; 60 hashb=Hash[r]-Hash[l-1]*h[lena]; 61 if(hasha==hashb)ans++; 62 // dbg(ans); 63 } 64 pf("%d ",ans); 65 } 66 }