poj_2001 Shortest Prefixes(Trie树应用)

【题目】

点击这里

【思路】

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值