利用 Trie 树对仅由小写字母构成的多个字符串按字典序排序
【利用 Trie 树对仅由小写字母构成的多个字符串按字典序排序】
本算法特别适合处理大量具有公共前缀的字符串排序场景,能有效利用前缀共享减少存储空间。
#include<bits/stdc++.h>
using namespace std;const int maxn=1e5+5;
int sn[maxn][26];
vector<string> v[maxn];
bool flag[maxn];
int idx;void insert(string s) {int p=0;for(int i=0; i<s.size(); i++) {int u=s[i]-'a';if(!sn[p][u]) sn[p][u]=++idx;p=sn[p][u];}flag[p]=true;v[p].push_back(s);
}void dfs(int rt) {if(flag[rt]) {sort(v[rt].begin(),v[rt].end());for(auto x:v[rt]) cout<<x<<endl;}for(int i=0; i<26; i++) {if(sn[rt][i]) dfs(sn[rt][i]);}
}int main() {int n;cin>>n;while(n--) {string s;cin>>s;insert(s);}dfs(0);return 0;
}/*
in:
5
ab
bc
abc
abc
efgout:
ab
abc
abc
bc
efg
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/138599488
https://blog.csdn.net/hnjzsyjyj/article/details/153636421