Dictionary tree Trie template

Dictionary tree Trie template

#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;
	}
}

Guess you like

Origin blog.csdn.net/weixin_44235989/article/details/108503155