字典树(Trie 树)→ 字符串排序

【题目描述】
输入若干个字符串,然后利用 Trie 树实现字符串排序。

【输入格式】
第一行一个整数 n,表示输入的字符串个数。
第二行输入 n 个字符串。

【输出格式】
按字典序输出 n 个字符串。

【算法分析】
● 先序遍历字典树,可实现字符串从小到大排序。
● 但是如下输入样例将失效,会输出错误的 big date do fat 结果。
6
fat
do dog dob date big
因此,本例代码需进行优化完善。

【算法代码】

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

const int maxn=4e5+5;
int sn[maxn][26]; //sn[p][u] indicates the serial number
int cnt[maxn]; //number of words ending in the current node
int flag[maxn];
int ans[maxn];
int idx;
int n;

void insert(string s) {
    int p=0; //root=0
    for(int i=0; i<s.size(); i++) {
        int u=s[i]-'a'; //a~z are mapped to 0~25
        if(!sn[p][u]) sn[p][u]=++idx;
        p=sn[p][u];
    }
    cnt[p]++;
    flag[p]=1;
}

void output(int n) {
    for(int i=1; i<=n; i++) {
        printf("%c",ans[i]+'a');
    }
    printf(" ");
}

void dfs(int dep,int p,int x) {
    ans[dep]=x;
    if(flag[p]==1) {
        output(dep);
        return;
    }

    for(int i=0; i<26; i++) {
        if(sn[p][i]) {
            dfs(dep+1,sn[p][i],i);
        }
    }
}

int main() {
    scanf("%d",&n);
    string str;
    for(int i=1; i<=n; i++) {
        cin>>str;
        insert(str);
    }
    dfs(0,0,0);

    return 0;
}

/*
in:
5
film cat abc tom go

out:
abc cat film go tom
*/



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/138599488
https://blog.csdn.net/hnjzsyjyj/article/details/138659402
https://blog.csdn.net/hnjzsyjyj/article/details/138647851
https://blog.csdn.net/hnjzsyjyj/article/details/138631374
https://www.cnblogs.com/re0acm/p/15349795.html

 

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值