字符串查找树(Trie)

字符串查找树(Trie)

例题:luogu2580

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
/*
luogu2580
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int n,m;
char name[55];
struct node
{
	char c;
	bool isend;
	bool called;
	int p[27];
	inline node(){c=0,memset(p,0,sizeof(p)),isend=called=false;}
	inline node(const char cc){c=cc,memset(p,0,sizeof(p)),isend=called=false;}
	inline void init(const char cc){c=cc;}
	inline int Map(char c){return c-97+1;}
	inline bool have(char c){return p[Map(c)]!=0;}
	inline node& nxt(char c);
	inline void add(char* s,int len,int pos);
	inline int query(char* s,int len,int pos);
}Trie[500053],ERROR('#');
node& root=Trie[0];
int size=0;
inline node& node::nxt(char c)
{
	if(have(c))
	{
		return Trie[p[Map(c)]];
	}
	else return ERROR;
}
inline void node::add(char* s,int len,int pos)
{
	if(pos+1>len)return;
	if(pos+1==len)
	{
		isend=true;
		return;
	}
	if(!have(s[pos+1]))
	{
		Trie[++size].init(s[pos+1]);
		p[Map(s[pos+1])]=size;
	}
	nxt(s[pos+1]).add(s,len,pos+1);
}
inline int node::query(char* s,int len,int pos)//1 means OK, 0 means WRONG, -1 means REPEAT
{
	if(pos+1>len)return 0;
	if(pos+1==len)
	{
		if(isend)
		{
			if(called)
			{
				return -1;
			}
			else
			{
				called=true;
				return 1;
			}
		}
		else return 0;
	}
	if(have(s[pos+1]))
		return nxt(s[pos+1]).query(s,len,pos+1);
	else return 0;
}
int main()
{
	freopen("luogu2580.in","r",stdin);
	//freopen("luogu2580.out","w",stdout);
	
	scanf("%d",&n);
	for(int i=1;i<=n;++i)
	{
		cin>>name;
		root.add(name,strlen(name),-1);
	}
	
	scanf("%d",&m);
	for(int i=1;i<=m;++i)
	{
		cin>>name;
		int ans=root.query(name,strlen(name),-1);
		if(ans==1)
			cout<<"OK\n";
		else if(ans==0)
			cout<<"WRONG\n";
		else if(ans==-1)
			cout<<"REPEAT\n";
		else 
			cout<<"ERROR"<<endl;
	}
	return 0;
}
0%