hdu 1800 Flying to the Mars trie

本文介绍了一种使用前缀树(Trie)的数据结构来高效处理字符串匹配问题的方法。通过构建前缀树,可以有效地存储和检索字符串集合。特别地,文章详细展示了如何为每个输入字符串创建节点,并在遍历过程中更新计数以找到出现频率最高的字符串前缀。

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

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct trie
{

    int cnt;
    trie *next[10];
};
int ans;
trie *rt=new trie;

void settrie(char *s)
{
    trie *p=rt,*t;
    int n=strlen(s),i,c;
    for(i=0;i<n-1;i++)
        if(s[i]!='0') break;
    for(; i<n; i++)
    {
        c=s[i]-'0';
        if(p->next[c]==NULL)
        {
            t=new trie;
            for(int j=0; j<10; j++)
            {
                t->next[j]=NULL;
            }
            t->cnt=0;
            p->next[c]=t;

        }
        p=p->next[c];
    }
    p->cnt++;
    if(p->cnt>ans)
        ans=p->cnt;
}

int main()
{
    int i,j,n;
    char s[50];
    while(~scanf("%d",&n))
    {
        ans=0;
        for(i=0;i<10;i++) rt->next[i]=NULL;
        rt->cnt=0;

        for(i=0;i<n;i++)
        {
            scanf("%s",s);
            settrie(s);
        }
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值