poj 2001 Shortest Prefixes

类型:Trie

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

来源:Rocky Mountain 2004

思路:对输入的字符串插入到字典树中,然后对每个字符串查找

结束条件:(1)当前字符只有一个分支(2)查到单词最后一个字符

// poj 2001 Shortest Prefixes
// ac 472K 0MS
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define FOR(i,a,b) for(i = (a); i < (b); ++i)
#define FORE(i,a,b) for(i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(i = (a); i > (b); --i)
#define FORDE(i,a,b) for(i = (a); i >= (b); --i)
#define CLR(a,b) memset(a,b,sizeof(a))

const int MAXN = 30000;
const int branchNum = 26;

char str[22];
char st[MAXN][22];
struct tree_node {
    int count;
    bool isstr;
    tree_node *next[branchNum];
}root, node[MAXN];
int p = 0;

void insert(char *word) {
    tree_node *location = &root;
    while(*word) {
        if(location->next[*word-'a'] == NULL) {
            node[p].count = 0;
            node[p].isstr = false;
            memset(node[p].next, NULL, sizeof(node[p].next));
            location->next[*word-'a'] = &node[p ++];
        }
        location = location->next[*word-'a'];
        location->count ++;
        word ++;
    }
    location->isstr = true;
}

void search(char *word) {
    tree_node *location = &root;
    CLR(str, '\0');
    int k = 0;
    while(*word && location) {
        location = location->next[*word-'a'];
        str[k++] += *word;
        word ++;
        if(location->count == 1)
            break;
    }
}

void solve () {
    int i = 0, j;
    char tmp[22];
    while(scanf(" %s", tmp) != EOF) {
        strcpy(st[i++], tmp);
        insert(tmp);
    }
    FOR(j, 0, i) {
        search(st[j]);
        printf("%s %s\n", st[j], str);
    }
}

int main() {
    solve();
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值