一、题目描述
Description
xzj学长和dzl一样,也想要背单词。但是同时xzj也觉得如果能用某个前缀唯一的表示一个单词,那么记这个前缀不就行了,所以xzj现在想知道对于每个单词他需要背的最短的可以唯一确定的前缀。
什么叫做唯一可以确定??比如说:对于单词 banana,和单词banb,那么能够用bana可以唯一的表示banana。
Input
T,代表T个单词。T<=2e4。
每个单词长度小于等于30。 所有单词均是小写字母构成。
Output
输出单词和单词的最小唯一表示前缀。
Sample Input Copy
2
banana
banb
Sample Output Copy
banana bana
banb banb
二、题解思路
一发就AC也是有点小激动,毕竟最近都不是很顺利。思路很简单,建个trie树,sum数组记录该点出现次数,vector保留所有单词,遍历查询,每次将单词依次拆分,直到那个点出现次数为1,可判断该部分能唯一标识该单词(当然如果单词走到末尾了,也能唯一标识)
三、AC代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int N = 2e4 + 50;
const int len = 35;
int trie[N * len][30], sum[N * len];
int cnt;
int n, m;
char str[35];
string tmp;
vector<string> ans;
void insert(char s[]) {
int root = 0;
for (int i = 0; s[i]; i++) {
int x;
x = s[i] - 'a';
if (!trie[root][x]) {
trie[root][x] = ++cnt;
}
root = trie[root][x];
sum[root]++;
}
}
int findd(string s) {
int root = 0;
for (int i = 0; s[i]; i++) {
int x;
x = s[i] - 'a';
if (!trie[root][x]) {
return 0;
}
root = trie[root][x];
}
return sum[root];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
while(n--){
cin >> str;
tmp = str;
ans.push_back(tmp);
insert(str);
}
for (int i = 0; i < ans.size(); i++) {
for (int j = 1; j <= ans[i].size(); j++) {
if (findd(ans[i].substr(0, j))== 1||j== ans[i].size()) {
cout << ans[i]<<" "<<ans[i].substr(0, j) << endl;
break;
}
}
}
return 0;
}