poj2001 Shortest Prefixes(Trie tree练手)

->题目请戳这里<-

题目大意:给若干个单词,求能唯一标识出他们的最小前缀。

题目分析:建颗字典树,查字典啊~

字典树练手题,废话不多说,详情请见代码:

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

const int N = 21;
typedef struct node
{
    struct node *next[26];
    int end,num;
}tree;
char s[N];
tree *root = NULL;
char str[10001][N];
int n;
int len;
void init(tree *t)
{
    t->end = t->num = 0;
    int i;
    for(i = 0;i < 26;i ++)
        t->next[i] = NULL;
}

void build(tree *t,int id)
{
    if(t != root)
        t->num ++;
    if(str[n][id] == '\0')
        return;
    if(t->next[str[n][id] - 'a'] == NULL)
    {
        t->next[str[n][id] - 'a'] = (tree *)malloc(sizeof(tree));
        init(t->next[str[n][id] - 'a']);
    }
    if(str[n][id + 1] == '\0')
    {
        t->next[str[n][id] - 'a']->end = 1;
        t->next[str[n][id] - 'a']->num ++;//提前预判结尾,也要标记上。wa出翔了。。。
    }
    else
        build(t->next[str[n][id] - 'a'],id + 1);

}

void print(tree *t)
{
    int i;
    printf("%d\n",t->num);
    for(i = 0;i < 26;i ++)
        if(t->next[i] != NULL)
            print(t->next[i]);
}

void deal(tree *t,int pos,int id)
{
    s[id] = str[pos][id];
    //printf("id:%d\n",id);
    //putchar(s[id]);
    //printf("%d\n",t->num);
    if(str[pos][id + 1] == '\0' || t->num == 1)
    {
        s[id + 1] == '\0';
        for(int i = 0;i <= id;i ++)
            putchar(s[i]);
        putchar('\n');
        //printf("%d\n",t->num);
        return;
    }
    else
    {
        deal(t->next[str[pos][id + 1] - 'a'],pos,id + 1);
    }
}

int main()
{
    int i;
    n = 0;
    root = (tree *)malloc(sizeof(tree));
    init(root);
    while(scanf("%s",str[n]) != EOF)
    {
        str[n][strlen(str[n])] = '\0';
        build(root,0);
        n ++;
    }
    //print(root);
    for(i = 0;i < n;i ++)
    {
        //printf("%s ",str[i]);
        int j = 0;
        while(str[i][j])
            putchar(str[i][j ++]);
        putchar(' ');
        deal(root->next[str[i][0] - 'a'],i,0);
       // printf("%s\n",s);
    }
    return 0;
}
//516K	47MS
/*
sb
sba
*/
样例太弱了,一个小错误检查好久。最后还是自己做了一组数据才检查出bug。。。

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