Trie树模板

//支持插入N个字符串,查询一个字符串是否存在,插入和查询都是o(length);
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<iostream> using namespace std; const int maxnode = 400000,sigma_size = 26;//最大结点数目,字符表的大小 const int maxn = 100;

int ch[maxnode][sigma_size];
int val[maxnode];
struct Trie {int sz; Trie(){sz = 1;memset(ch[0],0,sizeof(ch[0]));} int idx(char c) {return c-'a';} void insert(char *s, int v) { int u = 0,n = strlen(s); 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]=v; } int query(char *s) { int u = 0,n = strlen(s); for(int i = 0; i < n; ++i) { int c = idx(s[i]); if(!ch[u][c]){ return 0; } u = ch[u][c]; } return val[u]; } }t; char s[maxn]; int main() { return 0; }
原文地址:https://www.cnblogs.com/Norlan/p/4752075.html