poj_2001 Shortest Prefixes(Trie树应用)

来源:互联网 发布:淘宝假货投诉 编辑:程序博客网 时间:2024/05/12 15:08

【题目】

点击这里

【思路】

Trie树基本应用,先建树,而后对每个字符串查询,在查询过程中,取第一次碰到的尾缀单词数为1的结点之前的字符串作为前缀,如果查询完都没有,则取本身为前缀。

【代码】

#include<stdio.h>#include<stdlib.h>#include<string.h>typedef struct node{    char ch;    int num;    struct node *fChild, *rCousin;}* triNode;triNode newTree(char t){    triNode x=(triNode) malloc(sizeof(struct node));    x->ch=t; x->num=1; x->fChild=NULL; x->rCousin=NULL;    return x;}void addTree(triNode x, const char *s, int p){    int sLen=strlen(s),i;    for (i=p;i<sLen;i++)    {        x->fChild=newTree(s[i]);        x=x->fChild;    }}int main(){    triNode t=newTree('0');    int total=0,i,j;    char s[21],a[1001][21];    while (scanf("%s",s)!=EOF)    {        strcpy(a[total++],s);        int sLen=strlen(s);        triNode x=t,y;        for (i=0;i<sLen;i++)        {            y=x->fChild;            if (y==NULL) {addTree(x,s,i);break;}            do            {                if (y->ch==s[i]){x=y;x->num++;break;}                x=y; y=y->rCousin;            }while (y!=NULL);            if (y==NULL) {x->rCousin=newTree(s[i]); addTree(x->rCousin,s,i+1); break;}        }    }    for (i=0;i<total;i++)    {        printf("%s ",a[i]);        triNode x=t;        int sLen=strlen(a[i]);        for (j=0;j<sLen;j++)        {            x=x->fChild;            while (1){if (x->ch==a[i][j]) break; else x=x->rCousin;}            printf("%c",x->ch);            if (x->num==1) {printf("\n");break;}            if (j==sLen-1) printf("\n");        }    }    return 0;}


0 0
原创粉丝点击