poj 2001

字典树的题,敲过一两道基本上就会了。(我这里出于完成目的的心情,没有回收分配的空间)

#include <iostream>
#include <cstdio>
#include <cassert>
#include <cstring>

using namespace std;

struct node{
    int cnt;
    node *next[26];
    node(){
        cnt = 0;
        for(int i = 0; i < 26; ++i)
            next[i] = NULL;
    }
};
char s[2005][22];

void FindPrefix(char *str, int l, node *root){
    node *p = root;
    for(int i = 0; i < l; ++i){
        int t = str[i] - 'a';
        p = p->next[t];
        printf("%c", str[i]);
        if(p->cnt == 1)
            return ;
    }
    return ;
}

int main()
{
    node *root = new node;
    int tot = 0;
    while(scanf("%s", s[tot]) != EOF){
        node *p = root;
        for(unsigned i = 0; i < strlen(s[tot]); ++i){
            int t = s[tot][i] - 'a';
            if(p->next[t] == NULL){
                p->next[t] = new node;
            }
            p = p->next[t];
            p->cnt++;
        }
        tot++;
    }
    for(int i = 0; i < tot; ++i){
        printf("%s ", s[i]);
        int l = strlen(s[i]);
        FindPrefix(s[i], l,  root);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值