HDU 1004字典树

本文介绍了一种使用字典树解决HDU 1004问题的方法,通过C++代码实现了一个能够插入字符串并查找最热字符串的字典树。文章中的代码实现了字典树的基本操作,包括节点结构定义、插入和查询等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(http://www.elijahqi.win/2017/07/07/hdu-1004%E5%AD%97%E5%85%B8%E6%A0%91/%20%E2%80%8E)

#include<cstdio>
#include<cstring>
int n,nn,max,maxi;
char st[1100][20];
struct node{
    node *ch[26];int s;
    node(){
        for (int i=0;i<=25;++i) ch[i]=NULL;
        s=0;
    }
};
node *tree;
void insert1(char st[],int z){
    node *p=tree;
    for (int i=0;i<nn;++i) {
        if (p->ch[st[i]-'a']==NULL) {
            node *p1=new node();
            p->ch[st[i]-'a']=p1;
        }
        p=p->ch[st[i]-'a'];
    }
    p->s++;
}
void dfs(node *p){
    node *p1;
    for (int i=0;i<=25;++i){
        if (p->ch[i]!=NULL){
            p1=p->ch[i];
            if (p1->s>0){
                if (max<p1->s) max = p1->s;
            }
            dfs(p1);
        }

    }
}
int quest(char st[]){
    node *p=tree;
    for (int i=0;i<nn;++i) {
        if (p->ch[st[i]-'a']->s) {
            return p->ch[st[i]-'a']->s;

        }
        p=p->ch[st[i]-'a'];

    }
    return 0;
}
int main(){
    freopen("hdu1004.in","r",stdin);
    //freopen("hdu1004.out","w",stdout);
    while (1){
        scanf("%d",&n);
        if (n==0) break;
        tree=new node();
        for (int i=1;i<=n;++i){
            scanf("%s",st[i]);
            nn=strlen(st[i]);
            insert1(st[i],i);
        }
        max=0;
        //dfs(tree);
        for (int i=1;i<=n;++i){
            //printf("%d\n",quest(st[i]));
            int x=quest(st[i]);
            //printf("%d\n",x);
            if (max < x) {
                max = x;
                maxi = i;
            }
        }
    //    printf("%d",max);
    printf("%s\n",st[maxi]);
    //printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值