您的位置:首页 > 其它

poj 3461Oulipo

2016-07-21 14:43 337 查看
题目链接:http://poj.org/problem?id=3461

统计字符串出现的次数

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<vector>
#include<queue>
#include<iterator>
#include<vector>
#include<set>
#define dinf 0x3f3f3f3f
typedef long long ll;
//const int Max=(1<<16)+10;
using namespace std;
#define SIZE 100000005

const int N = 100000005;
int m_next
;
char S
,T
;
int slen, tlen;

void getNext()
{
int j, k;
j = 0; k = -1; m_next[0] = -1;
while(j < tlen)
if(k == -1 || T[j] == T[k])
m_next[++j] = ++k;
else
k = m_next[k];

}
/*
返回模式串T在主串S中首次出现的位置
返回的位置是从0开始的。
*/
int KMP_Index()
{
int i = 0, j = 0;
getNext();

while(i < slen && j < tlen)
{
if(j == -1 || S[i] == T[j])
{
i++; j++;
}
else
j = m_next[j];
}
if(j == tlen)
return i - tlen+1;
else
return -1;
}
/*
返回模式串在主串S中出现的次数
*/
int KMP_Count()
{
int ans = 0;
int i, j = 0;

if(slen == 1 && tlen == 1)
{
if(S[0] == T[0])
return 1;
else
return 0;
}
getNext();
for(i = 0; i < slen; i++)
{
while(j > 0 && S[i] != T[j])
j = m_next[j];
if(S[i] == T[j])
j++;
if(j == tlen)
{
ans++;
j = m_next[j];
}
}
return ans;
}
int main()
{

int TT;
int i, cc;
string str;
cin>>TT;
while(TT--)
{
getchar();

scanf("%s %s",&T,&S);
slen = strlen(S);
tlen = strlen(T);
printf("%d\n",KMP_Count());

//cout<<"模式串T在主串S中首次出现的位置是: "<<KMP_Index()/2+1<<endl;
//cout<<"模式串T在主串S中出现的次数为: "<<KMP_Count()<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: