nefu 197 KMP

时间:2023-03-08 21:54:09
nefu 197 KMP

Description

在信息检索系统中一个很重要的环节就是关键字符串的查找,从而很多对自己有用的信息。给你一个很长的一段文字, 和一个关键信息字符串,现在要你判断这段文字里面是否有关键字符串。

Input

输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一段文字(中间不含空格,长度不超过1000),和一个关键信息字符串(长度不超过10)

Output

输出这段文字里面是否有关键字符串,如果有则输出Yes,否者输入No,具体细节见样例。

Sample Input

3
songpanda pan
hudzpdgj huz
aabdcc ad

Sample Output

Case #1: Yes
Case #2: No
Case #3: No

KMP:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
char str1[],str2[];
int next[];
void getnext(int L)
{
int i=,j=-;
next[]=-;
while(i<L)
{
if(j==- || str2[j]==str2[i])
{
i++;
j++;
if(str2[i]!=str2[j]) next[i]=j;
else next[i]=next[j];
}
else j=next[j];
}
}
int kmp(int L1,int L2)
{
getnext(L2);
int i=,j=;
while(i<L1)
{
if(j==- || str1[i]==str2[j]) i++,j++;
else j=next[j];
if(j==L2) return ;
}
return ;
}
int main()
{
int n;
int k=;
scanf("%d",&n);
getchar();
while(n--)
{
scanf("%s%s",str1,str2);
int ans=kmp(strlen(str1),strlen(str2));
if(ans==) printf("Case #%d: Yes\n",++k);
else printf("Case #%d: No\n",++k);
}
return ;
}