POJ2001 Shortest Prefixes(字典树)

Shortest Prefixes

题目链接:

http://poj.org/problem?id=2001

解题思路:

字典树模板!!!

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

struct node{
    int cnt;
    struct node *next[26];
    node(){
        cnt = 0;
        memset(next,0,sizeof(next));
    }
};

node *root = NULL;
char  str[1010][21];

void build(char *s){
    node *p = root,*tmp;
    int l = strlen(s);
    for(int i = 0; i < l; i++){
        if(p->next[s[i]-'a'] == NULL){
            tmp = new node;
            p->next[s[i]-'a'] = tmp;
        }
        p = p->next[s[i]-'a'];
        p->cnt++;
    }
}

void findtrie(char *s){
    node *p = root;
    int l = strlen(s);
    for(int i = 0; i < l; i++){
        printf("%c",s[i]);
        p = p->next[s[i]-'a'];
        if(p->cnt == 1)
            break;
    }
    printf("\n");
}

int main(){
    root = new node;
    int num = 0;
    while(scanf("%s",str[num++]) != EOF)
        build(str[num-1]);
    for(int i = 0; i < num; i++){
        printf("%s ",str[i]);
        findtrie(str[i]);
    }
    return 0;
}


你可能感兴趣的:(字典树)