您的位置:首页 > 其它

hdu2203(KMP模板)

2015-10-10 01:09 375 查看
参考代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<sstream>
#include<string>
#include<bitset>
using namespace std;

typedef long long LL;

const LL LINF = (1LL <<63);
const int INF = 1 << 31;

const int NS = 200010;
const int MS = 19;
const int MOD = 1000000007;

char s1[NS], s2[NS];
int snext[NS];

void getNext(char* pattern, int* next)
{
//未优化的next数组,字符下标从0开始
int len = strlen(pattern);
int j = -1;
next[0] = -1;
for(int i = 0; i < len;)
{
while(j >= 0 && pattern[i] != pattern[j])
{
j = next[j];
}
i++, j++;
next[i] = j;
}
}

void getOptNext(char* pattern, int* next)
{
//优化的next数组,字符下标从0开始
int len = strlen(pattern);
int j = -1;
next[0] = -1;
for(int i = 0; i < len;)
{
while(j >= 0 && pattern[i] != pattern[j])
{
j = next[j];
}
i++, j++;
if(pattern[i] != pattern[j])
{
next[i] = j;
}
else
{
next[i] = next[j];
}
}
}

bool KMP(char* target, char* pattern, int* next)
{
int n = strlen(target);
int m = strlen(pattern);

int j = 0;
for(int i = 0; i < n;)
{
if(target[i] == pattern[j])
{
i++, j++;
if(m == j)
{
return true;
}
}
else
{
j = next[j];
if(j < 0)
{
i++, j++;
}
}
}
return false;
}

int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
#endif

while(~scanf("%s %s", s1, s2))
{
int n = strlen(s1);
for(int i = 0; i < n; i++)
{
s1[i + n] = s1[i];
}
n <<= 1;
s1
= '\0';
getOptNext(s2, snext);
bool ans = KMP(s1, s2, snext);

if(ans)
{
puts("yes");
}
else
{
puts("no");
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: