博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[hdu][2203][亲和串]

Posted on 2012-02-15 20:54  紫华弦筝  阅读(143)  评论(0编辑  收藏  举报

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2203

给定两个字符串s1和s2,如果能通过s1循环移位,使s2包含在s1中,那么我们就说s2 是s1的亲和串。

View Code
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int MAXV = 200000+10;

void kmp(char in[], int len, int path[])
{
int i, j = -1; path[0] = -1;
for (i = 1; i < len; i++)
{
while (j >= 0 && in[j+1] != in[i]) j = path[j];
if (in[j+1] == in[i]) j++;
path[i] = j;
}
}

char s1[MAXV], s2[MAXV];
int p[MAXV];

int main()
{
int l1, l2, ok;
while (scanf("%s%s", s1, s2) != EOF)
{
l1 = strlen(s1); l2 = strlen(s2);
ok = 0;
if (l1 < l2)
{
printf("no\n");
continue;
}
kmp(s2, l2, p);
int i, j=-1;
for (i = l1; i < l1+l2; i++) s1[i] = s1[i-l1];
s1[i] = '\0';
for (i = 0; i < l1+l2 && !ok; i++)
{
while (j > -1 && s1[i] != s2[j+1]) j = p[j];
if (s2[j+1] == s1[i]) j++;
if (j == l2-1)
{
printf("yes\n");
ok = 1;
}
}
if (!ok) printf("no\n");
}
return 0;
}