ZOJ 2876 Phone List(trie树)

判断是否某个电话是另一个电话的前缀.

典型的trie树应用.

#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
const int maxn = 10001;
struct node{
    bool flag;
    node * chd[10];
}trie[maxn * 6], *root;
int n, cnt;
char buf[30];

void init(){
    memset(trie, 0, sizeof(trie));
    cnt = 0;
    root = &trie[cnt++];
}
bool addWord(){
    int len = strlen(buf), f = 0;
    node * p = root;
    for (int i = 0; i < len; ++i){
        if(p->chd[buf[i] - '0'] == NULL){
            p->chd[buf[i] - '0'] = &trie[cnt++];
            p = p ->chd[buf[i] - '0'];
            f = 1;	//建立了新结点,至少已经不是别人的前缀了
        }else{
            p = p ->chd[buf[i] - '0'];
        }
        if(p->flag){ //字符路径上有一个单词是当前单词的前缀
            return false;
        }
    }
    p->flag = true;
    if(!f)return false;//说明这个单词没有建过新结点,肯定是其他单词的前缀
    return true;
}
int main(){
    int T;
    scanf("%d", &T);
    while (T--){
        init();
        scanf("%d", &n);
        int f = 0;
        while (n--){
            scanf("%s", buf);
            if(!addWord()){
                f = 1;
            }
        }
        if(f){
            printf("NO\n");
        }else{
            printf("YES\n");
        }
    }
    return 0;
}

    原文作者:Trie树
    原文地址: https://blog.csdn.net/zxjcarrot/article/details/8907981
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞