有 \(n\) 个长度为 \(9\) 且只包含数字字符且 互不相同 的串。需要对于每个串找到一个 长度最短 的识别码,使得这个识别码是且仅是这个串的子串。
将每个串的所有后缀加入字典树中
然后对于每个串,跑它的每个子串,如果跑到某个位置,子树中只剩下与自己同类的,就可行,最后对所有可行取最小值
用 map 保存每个子串是谁的,如果同时是两个以上的,这个子串就不能用
最后遍历 map 对答案进行更新
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int n;
string a[N];
map<string,int> mp;
signed main() {
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) {
for(int j=0;j<9;j++) {
for(int k=1;k+j<=9;k++) {
string tmp=a[i].substr(j,k);
if(mp[tmp]==-1) continue;
if(mp[tmp]==0) mp[tmp]=i;
else if(mp[tmp]!=i) mp[tmp]=-1;
}
}
}
for(auto i:mp) {
if(i.second!=-1) {
if(i.first.length()<a[i.second].length()) {
a[i.second]=i.first;
}
}
}
for(int i=1;i<=n;i++) {
cout<<a[i]<<endl;
}
}
[CF858D] Polycarp's phone book - STL
原文:https://www.cnblogs.com/mollnn/p/12800108.html