P1481 魔族密码 (字典树 模板)

题目链接:https://www.luogu.com.cn/problem/P1481

题意

  • 给你n个单词。
  • 如果在一个由一个词或多个词组成的表中,除了最后一个以外,每个单词都被其后的一个单词所包含,即前一个单词是后一个单词的前缀,则称词表为一个词链。
  • 求最长词链所包含的单词数。

思路

  • 字典树模板题。
  • 插入完了过后求一下经过的总的字符串个数,并更新其最大值

AC代码

数组篇

#include<bits/stdc++.h>
using namespace std;
const int N = 2020;
struct node{
    int next[27];//下一个字符位置
    int num;//代表以当前字母为结尾的单词在树中出现多少次
int ans,tot;
void add_node(string s){
    int len=s.size(),pos=0;
    int res=0;
    for(int i=0;i<len;i++){
        int tmp=s[i]-'a'+1;
        if(!t[pos].next[tmp])t[pos].next[tmp]=++tot;
        pos=t[pos].next[tmp];
        res+=t[pos].num;//计算词链中包含的单词数
    }
    t[pos].num++;
    ans=max(ans,res+1);//res+1,加的是当前加入的字符串
}
int main(){
    int n;cin>>n;
    for(int i=1;i<=n;i++){
        string s;cin>>s;
        add_node(s);
    }
    cout<<ans<<endl;
    system("pause");
    return 0;
}

链表篇

#include<bits/stdc++.h>
using namespace std;
struct node{
    int num=0; //代表以当前字母为结尾的单词在树中出现多少次
    int flag=0;//标记,看是不是最后一个字母
    node *next[27];
};
int ans;
//建树初始化
node* creat(){
    node *root = new node();
    root->flag=0;
    root->num=0;
    memset(root->next,NULL,sizeof(root->next));
    return root;
}

//插入一个单词
void insert(node *root,char *word){
    int res=0;
    node *location=root;
    while(*word){
        if(location->next[*word-'a']==NULL){
            node *tmp=creat();
            location->next[*word-'a']=tmp;
        }
        location=location->next[*word-'a'];
        word++;
        if(location->num)res+=location->num;
        //location->num++;
    }
    location->num++;
    ans=max(ans,res+location->num);
}

//查询关键词出现的次数
int search(node *root,char *word){
    node *location=root;
    while(location && *word){
        location = location -> next[*word-'a'];
        word++;
    }
    if(location && location->flag)return location->num;
    else{
        cout<<"error"<<endl;
        return 0;
    }
}

//释放内存
void Delete(node *root){
    for(int i=0;i<26;i++){
        if(root->next[i]){
            Delete(root->next[i]);
        }
    }
    delete root;
}
int main(){
    int n;cin>>n;
    node *root=creat();
    for(int i=1;i<=n;i++){
        char s[1005];cin>>s;
        insert(root,s);
    }
    cout<<ans<<endl;
    system("pause");
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值