DEV正常,洛谷编译失败?
查看原帖
DEV正常,洛谷编译失败?
808466
htdlz楼主2023/8/28 14:56

谢谢

#include<bits/stdc++.h>
using namespace std;

struct node
{
	node *fail;
	node *ch[27];
	int count;
	node()
	{
		memset(ch,'\0',sizeof(ch));
		fail='\0';
		count=0;
	}
};

node *root,*sroot;
void init()
{
	root=new node;sroot=new node;
	sroot->count=-1;root->fail=sroot;
	for(int i=0;i<26;i++)sroot->ch[i]=root;
}

void build(char* s)
{
	node *t=root;
	int l=strlen(s);
	for(int i=0;i<l;i++)
	{
		if(t->ch[s[i]-'a']=='\0')
			t->ch[s[i]-'a']=new node;
		t=t->ch[s[i]-'a'];
	}
	t->count++;
}

queue<node*>q;
void build_ac()
{
	q.push(root);
	while(!q.empty())
	{
		node* u=q.front();
		q.pop();
		for(int i=0;i<26;i++)
		{
			if(u->ch[i])
			{
				u->ch[i]->fail=u->fail->ch[i];
				q.push(u->ch[i]);
			}
			else
			{
				u->ch[i]=u->fail->ch[i];
			}
		}
	}
}

int find(char* s)
{
	int ans=0;
	node* t=root;
	int l=strlen(s);
	for(int i=0;i<l;i++)
	{
		t=t->ch[s[i]-'a'];
		for(node* u=t;u->count!=-1;u=u->fail)
		{
			ans+=u->count;
			u->count=-1;
		}
	}
	return ans;
} 

int main()
{
	init();
    int n;
    cin>>n;
    char s[20];
    for(int i=1;i<=n;i++)
	{
		scanf("%s",&s);
		build(s);
	} 
	build_ac();
	scanf("%s",&s);
	printf("%d",find(s));
    return 0;
}

2023/8/28 14:56
加载中...