简单字典树 模板

#include<bits/stdc++.h>
using namespace std;
const int N = 2000000+10;
struct node{
    node *next[26];
    int num;
    bool ok;
    node() {
        for(int i=0;i<26;i++) {
            next[i] = NULL;
        }
        num = 0, ok = 0;
    }
};
int n;
char s[N];
node *root;
int ans = 0;
void dfs(node *rt) {
    if(rt == NULL) return ;
    if(rt->num <= 5) {
        ans++;
        return ;
    }
    for(int i=0;i<26;i++) {
        dfs(rt->next[i]);
    }
}

void ins(char *s) {
    int len = strlen(s);
    node * rt = root;
    for(int i=0;i<len; i++) {
        int id = s[i] - 'a';
        if(rt->next[id] == NULL) {
            rt->next[id] = new node();
        }
        rt = rt->next[id];
        rt->num++;
    }
    rt->ok = true;
}

void del(node *rt) {
    if(rt == NULL) return ;
    for(int i=0;i<26;i++) {
        if(rt->next[i] != NULL) del(rt->next[i]);
    }
    delete p;
}

int main () {
    int T; scanf("%d",&T);
    while (T--) {
        ans = 0;
        scanf("%d",&n);
        root = new node();
        for(int i=0;i<n;i++)
            scanf("%s",s) , ins(s);
        for(int i=0;i<26;i++) {
            if(root->next[i]!=NULL)
                dfs(root->next[i]);
        }
        cout << ans<<endl;
    }
    return 0;
}

 

posted @ 2018-08-18 11:19  Draymonder  阅读(195)  评论(0编辑  收藏  举报