poj 2001 Shortest Prefixes

来源:互联网 发布:淘宝时尚女装店名 编辑:程序博客网 时间:2024/06/05 19:59

类型: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;}