[恢]hdu 2203

2011-12-30 02:41:06

地址:http://acm.hdu.edu.cn/showproblem.php?pid=2203

题意:中文,字符串比较。

mark:把第一个串复制一次接在自己后面。然后字符串比较。

据说数据很水?!我就暴了一下,结果TLE。。。好吧,刚学了KMP,用上试试,果断0ms,威力果然不小,开心。

代码:

# include <stdio.h>
# include <string.h>


char s1[200010], s2[100010] ;
char buff[100010] ;
int next[100010] = {-1} ;


void getnext(char *s)
{
int i, j = -1 ;
for (i = 1 ; s[i] ; i++)
{
while (j != -1 && s[i] != s[j+1]) j = next[j] ;
if (s[j+1] == s[i]) j++ ;
next[i] = j ;
}
}


int kmp(char p[], char s[], int len1, int len2)
{
int i, j = -1 ;
getnext(s) ;
for (i = 0 ; i < len1 ; i++)
{
while (j != -1 && p[i] != s[j+1]) j = next[j] ;
if (p[i] == s[j+1]) j++ ;
if (j == len2-1) return i-len2+1 ;
}
return -1 ;
}


int main ()
{
int rst ;
while (~scanf ("%s%s", s1, s2))
{
strcpy (buff, s1) ;
strcat(s1, buff) ;
rst = kmp (s1, s2, strlen(s1), strlen(s2)) ;
if (rst != -1) puts ("yes") ;
else puts ("no") ;
}
return 0 ;
}



原文地址:https://www.cnblogs.com/lzsz1212/p/2315410.html