欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

字典树 Trie 模版

程序员文章站 2022-05-19 19:17:41
...

字典树 Trie 模版

#include<iostream>
#include <sstream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define lowbit(x) x&-x
//#define int long long

const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
//const ll inf=0x3f3f3f3f;
const int maxn=1e2+10;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

struct Trie
{
	int ch[maxn][26];
	int val[maxn];
	int sz;
	Trie() { sz=1; memset(ch[0], 0, sizeof(ch[0])); }
	int idx(char c) { return c-'a'; }
	
	//插入
	void insert(string s)
	{
		int u=0,n=s.length();
		for(int i=0;i<n;i++)
		{
			int c=idx(s[i]);
			if(!ch[u][c])
			{
				memset(ch[sz], 0, sizeof(ch[sz]));
				val[sz]=0;
				ch[u][c]=sz++;
			}
			u=ch[u][c];
		}
		val[u]=1;
	}
	// 查询
	int query(string s)
	{
		int n=s.length(),p=0;
		for(int i=0;i<n;i++)
		{
			int c=idx(s[i]);
			if(!ch[p][c]) return 0;
			p=ch[p][c];
		}
		return val[p]==1;
	}
};

int main()
{
	Trie tree;
	int n;
	cin >> n;
	for(int i=0;i<n;i++)
	{
		string tmp; cin >> tmp;
		tree.insert(tmp);
	}
	string q;
	while(cin >> q)
	{
		if(tree.query(q)) cout << "YES" << endl;
		else cout << "NO" << endl;
	}
}
相关标签: 字符串