FZU 1926 填空【KMP】

题目链接:http://acm.fzu.edu.cn/problem.php?pid=1926

与一般的KMP不同,这是一个单词一个单词比较

#include<cstring>
#include<cstdio>
#include<string>
#include<algorithm>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const double PI=acos(-1.0);
const int mod=1e9;
const int N=1005;

string s[N],z[N];
//用string型,把一个单词当作一个字母,
//string型能直接相比较
int len_s,len_z;
char str[N];
int cut,Next[N];

void get_Next()
{
    int i=0,j=-1;
    Next[0]=-1;
    while(i<len_z)
    {
        if(j==-1||z[i]==z[j]||z[i]=="_"||z[j]=="_")
            Next[++i]=++j;
        else
            j=Next[j];
    }
}

int KMP()
{
    int i=0,j=0,ans;
    get_Next();
    while(i<len_s&&j<len_z)
    {
        if(j==-1||s[i]==z[j]||z[j]=="_")
        {
            i++;
            j++;
        }
        else
            j=Next[j];
        if(j==len_z) return 1;
    }
    return 0;
}

int main()
{
    int T,cas=0,q;
    scanf("%d",&T);
    while(T--)
    {
        cut=0;
        while(scanf("%s",str))
        {
            if(strcmp(str,"@")==0)//如果输入字符串=@  跳出循环
                break;
            s[cut++]=string(str);
        }
        len_s=cut;
        scanf("%d",&q);
        printf("Case %d:\n",++cas);
        while(q--)
        {
            cut=0;
            while(~scanf("%s",str))
            {
                if(strcmp(str,"@")==0)//同上
                    break;
                z[cut++]=string(str);
            }
            len_z=cut;
            if(KMP()) printf("YES\n");
            else printf("NO\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41984014/article/details/88997560
今日推荐