LG4341/BZOJ2251 「BJWC2010」外星联络 Trie

问题描述

LG4341

BZOJ2251

BZOJ需要权限号


题解

字符串的性质:一个字符串\(s\)所有的字串,等于\(s\)所有后缀的前缀。

枚举这个字符串的每一个后缀,将其插入一个\(\mathrm{Trie}\)

在插入\(\mathrm{Trie}\)的过程中可以非常方便的维护这个后缀的每个前缀。

最后从\(root\)开始对整棵\(\mathrm{Trie}\)进行一次遍历即可。


\(\mathrm{Code}\)

#include<bits/stdc++.h>
using namespace std;

void read(int &x){
    x=0;char ch=1;int fh;
    while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
    if(ch=='-') fh=-1,ch=getchar();
    else fh=1;
    while(ch>='0'&&ch<='9'){
        x=(x<<1)+(x<<3)+ch-'0';
        ch=getchar();
    }
    x*=fh;
}

char s[3007];
int ch[10000000][2],tot,root;//错误笔记:一开始数组开小十倍
int n,cnt[10000000];
void build(){
    root=++tot;
}

int chk(char s){
    return s-'0';
}

void insert(int pla){
    int p=root;
    for(register int i=pla;i<=n;i++){
        int k=chk(s[i]);
        if(!ch[p][k]) ch[p][k]=++tot;
        p=ch[p][k];++cnt[p];
    }
}

void dfs(int x){
    if(cnt[x]>1&&x!=root) cout<<cnt[x]<<endl;
    if(ch[x][0]) dfs(ch[x][0]);
    if(ch[x][1]) dfs(ch[x][1]);
}

int main(){
    ios::sync_with_stdio(0);
    build();
    cin>>n;cin>>(s+1);
    for(register int i=n;i>=1;i--){
        insert(i);
    }
    dfs(root);
    return 0;
}

转载于:https://www.cnblogs.com/liubainian/p/11479698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值