动态建树之——寻找最长公共前缀

题目:poj2001

题意:寻找最长公共前缀

解答:大概是最简单的字典树的建立、查找

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
const int sonnum = 26,base = 'a';
char a[10010][26];
using namespace std;
struct Trie//定义字典树的节点
{
    int num;
    bool terminal;
    struct Trie *son[sonnum];
};
Trie *NewTrie()//建立一个字典树
{
    Trie *temp = new Trie;///
    temp -> num = 1;
    temp -> terminal = false;
    for(int i = 0;i < sonnum;i++)
        temp -> son[i] = NULL;
    return temp;
}

void Insert(Trie *pnt,char *s,int len)//插入单词
{
    Trie *temp = pnt;
    for(int i = 0;i < len;i++)
    {
        if(temp -> son[s[i]-base] == NULL)
            temp -> son[s[i]-base] = NewTrie();///
        else
            temp -> son[s[i]-base] -> num++;
        temp = temp -> son[s[i]-base];
    }
    temp -> terminal = true;
}
Trie *Find(Trie *pnt,char *s,int len)//查找单词
{
    Trie *temp = pnt;
    for(int i = 0;i < len;i++)
    {
        if(temp -> son[s[i]-base] -> num == 1)
        {
            printf("%c",s[i]);
            return temp;
        }
        printf("%c",s[i]);
        temp = temp -> son[s[i]-base];
    }
    return temp;
}
int main()
{
    int cnt = 0;
    char t[110];
    Trie *tree = NewTrie();///
    while(~scanf("%s",a[cnt]))
    {
        if(a[cnt][0] == '0')
            break;
        Insert(tree,a[cnt],strlen(a[cnt]));
        cnt++;
    }
    for(int i = 0;i < cnt;i++)
    {
        printf("%s ",a[i]);
        Find(tree,a[i],strlen(a[i]));
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值