POJ 3630 Phone List(字典树)

给你几个电话号码,判断是否存在某个电话号码是其他任一电话号码的前缀,若存在则输出“YES”, 若不是则输出“NO”、

这题依旧用字典树,每个结点计算该位该号码出现的次数,全部插入字典树之后,遍历所有电话号码串,如果某个结束点的值大于1,则说明确实存在这种情况,则输出。


#include <cstdio>
#include <cstdlib>
#include <cstring>

const int branchNum = 10;
const int trieNodeNum = 110000;

struct Trie_node{
    int isStr;
    int next[branchNum];
}trie[trieNodeNum];
int trieTop = 0;
char str[11000][13];

void init(){
    int i;

    trieTop = 0;
    for (i = 0; i < trieNodeNum; i++){
        trie[i].isStr = 0;
        for (int j = 0; j < 10; j++){
            trie[i].next[j] = -1;
        }
    }
    memset(str, 0, sizeof(str));
}

void insert(const char *word){

    int location = 0;

    trie[location].isStr ++;
    while (*word){
        if (trie[location].next[*word - '0'] == -1){
            trie[location].next[*word - '0'] = ++trieTop;
        }
        location = trie[location].next[*word - '0'];
        trie[location].isStr ++;
        word++;
    }
}

int search(const char *word){
    int location = 0;
    int len = strlen(word);

    while (*word && location != -1){
        location = trie[location].next[*word - '0'];
        word ++;
    }
    return trie[location].isStr;
}

void print(const char *word){
   int location = 0;
   const char *a = word;

    while (*word && location != -1){
        location = trie[location].next[*word - '0'];
        printf("%d %c %d\n", word - a, *word, trie[location].isStr);
        word++;
    }
}

int main(void){
    int casenum, ii;
    int nodenum;
    int i, j;
    int flag = 0;

    scanf("%d", &casenum);
    for (ii = 0; ii < casenum ; ii++){
        init();
        scanf("%d", &nodenum);
        for (i = 0; i < nodenum ; i++){
            scanf("%s", str[i]);
            insert(str[i]);
        }
        for (i = 0, flag = 0; i < nodenum && flag == 0; i++){
            //printf("%s :%d\n", str[i], search(str[i]));
            //print(str[i]);
            if (search(str[i]) > 1){
                printf("NO\n");
                flag = 1;
                break;
            }
        }
        if (flag == 0){
            printf("YES\n");
        }
    }
    return 0;
}


你可能感兴趣的:(POJ 3630 Phone List(字典树))