http://poj.org/problem?id=3461
先来一发KMP算法:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <iostream>
#include <cmath>
#include <map>
#include <queue>
using namespace std;
#define ls(rt) rt*2
#define rs(rt) rt*2+1
#define ll long long
#define ull unsigned long long
#define rep(i,s,e) for(int i=s;i<e;i++)
#define repe(i,s,e) for(int i=s;i<=e;i++)
#define CL(a,b) memset(a,b,sizeof(a))
#define IN(s) freopen(s,"r",stdin)
#define OUT(s) freopen(s,"w",stdin)
const int MAXN = 1000000+100;
char T[MAXN],P[MAXN],tmp[MAXN];//T--文本,P--模板串
int fail[MAXN];
void getfail()
{
int m=strlen(P);
fail[0]=fail[1]=0;
for(int i=1;i<m;i++)
{
int j=fail[i];
while(j && P[i]!=P[j])j=fail[j];
fail[i+1]=P[i]==P[j]?j+1:0;
}
}
int Find()
{
int ans=0;
int n=strlen(T),m=strlen(P);
if(n<m)
{
strcpy(tmp,T);
strcpy(T,P);
strcpy(P,tmp);
}
getfail();
int j=0;
for(int i=0;i<n;i++)
{
while(j && P[j]!=T[i])j=fail[j];
if(P[j] == T[i])j++;
if(j==m)//printf("%d\n",i-m+1);//find it
ans++;
}
return ans;
}
int main()
{
//IN("poj3461.txt");
int n;
while(~scanf("%d",&n))
{
while(n--)
{
scanf("%s%s",P,T);
printf("%d\n",Find());
}
}
return 0;
}
再来一发字符串HASH
我的字符串HASH模板在http://blog.csdn.net/u011026968/article/details/38460357
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <iostream>
#include <cmath>
#include <map>
#include <queue>
using namespace std;
#define ls(rt) rt*2
#define rs(rt) rt*2+1
#define ll long long
#define rep(i,s,e) for(int i=s;i<e;i++)
#define repe(i,s,e) for(int i=s;i<=e;i++)
#define CL(a,b) memset(a,b,sizeof(a))
#define IN(s) freopen(s,"r",stdin)
#define OUT(s) freopen(s,"w",stdin)
#define ull unsigned long long
const ull B = 1e8+7; /*according to the book*/
const int MAXN = 1000000+100;
char a[MAXN],b[MAXN],tmp[MAXN];
int hashfind()
{
int ans=0;
int al=strlen(a),bl=strlen(b);
if(al>bl)
{
strcpy(tmp,a);
strcpy(a,b);
strcpy(b,tmp);
}
ull t=1,ah=0,bh=0;
for(int i=0;i<al;i++)
{
t*=B;
ah=ah*B+a[i];
bh=bh*B+b[i];
}
for(int i=0;i+al<=bl;i++)
{
if(ah==bh)ans++;
if(i+al<bl)bh=bh*B+b[i+al]-b[i]*t;
}
return ans;
}
int main()
{
//IN("poj3461.txt");
int n;
while(~scanf("%d",&n))
{
while(n--)
{
scanf("%s%s",a,b);
printf("%d\n",hashfind());
}
}
return 0;
}