`

poj 2001

 
阅读更多

题意:给出n个单词(1<=n<=1000),求出每个单词的非公共前缀,如果没有,则输出自己。

 

思路:基础的trie。

 

只要基本了解Trie的构造与查找过程,就可以去做了。

代码如下所示:

#include<iostream>
using namespace std;
const int Max = 1002;
const int branchNum = 26;

struct tree_node
{
    int count;   // 记录用到这个节点的单词数量,如果=1,则证明其为这个单词唯一的节点。
    tree_node *next[branchNum];
}root,node[20*Max];
int p = 0;      //  静态建树的特点,记录用了几个tree_node,则下一个节点为node[p]。

void insert(char *word)
{
    tree_node *location = &root; //  起初先指向根,再一层层向下查找。
    while(*word)
	{
        if(location->next[*word-'a'] == NULL)
		{
            node[p].count = 0;//  初始化新节点
            location->next[*word-'a'] = &node[p ++];
        }
        location = location->next[*word-'a'];
        location->count ++;
        word ++;
    }
}

void search(char *word)
{
    tree_node *location = &root;
    while(*word && location)
	{
        if(location->count == 1) 
			break;
        printf("%c", *word);
        location = location->next[*word-'a'];
        word ++;
    }
    printf("\n");
}

int main()
{
    char word[Max][21];
    int i, k = 0;
    while(scanf("%s", word[k])!= EOF)
	{
        insert(word[k]);
		k ++;
    }
    for(i = 0; i < k; i ++)
	{
        printf("%s ", word[i]);
        search(word[i]);
    }
    return 0;
}


 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics