短名字
0.总结
Get to the key point firstly, the article comes from LawsonAbs!
1.题意
Bob is making a video conference software. Whenever a new person joins the conference, Bob displays the person’s name in the interface.
However, displaying full name is tedious and takes much space. So he decided to display the shortest prefix which doesn’t match with any prefix of any person who has joined earlier.
Let’s suppose the first person to enter the conference is alvin.Now suppose next person to join is alice.
The shortest prefix of alice that doesn’t match with any prefix of alvin is ali.
If the full name of a new person matches completely with the full name of any person who has joined earlier, he will display the full name and add a suffix which indicates how many times the same name has occurred in the list so far. For example, if another person name alvin joins, the list will look like this:
You are given the list of the persons who have joined the call in the chronological order. Your task is to figure out how the final list looks like.
简短的总结一下题意。
其实就是输出不重复的最大前缀。
2.分析
主要有两种做法,分别是字典树和map
。
2.1 字典树
暂无
2.2 map
主要实现过程如下:
- step 1.判断每个人姓名的前缀是否出现在map中,如果出现过,则往下遍历,直到分析完整个字符串;否则直接输出,并且把当前的这个前缀写到map中。
- step 2.接着分析下一个字符串。
例如:对于alvin
这个人,依次写入
a
al
alv
alvi
alvin
并依次判断上述的字符串是否已经写到map中了,如果写过了,则依次往下遍历,直到遍历完整个字符串。如果整个姓名都已经出现过,则先输出姓名再输出该姓名出现的次数。
例如对于样例1
输入样例1
3
alvin
alice
alvin
输出样例1
a
ali
alvin 2
3.代码
#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string,int> res;
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
string s;
for(int i = 0;i < n;i++){
cin >> s;
string temp = "";
int flag = 0;
for(int j = 0;j < s.length()-1;j++){
temp += s[j];
if(res.find(temp) == res.end() ){
if(flag == 0) {
flag = 1;
cout << temp <<"\n";
}
res[temp] = 0;
}
}
if(flag == 0){
if( res[s] == 0 || res.find(s) == res.end() ){
cout << s<<"\n";
res[s] = 1;
}
else{
int idx = res[s] + 1;
cout << s << " "<< idx<<"\n";
res[s] = idx;
}
}
else//
res[s] = 1;
}
}
4.测试用例
输入
5
alvin
alvin
alv
alvin
alv
输出
a
alvin 2
alv
alvin 3
alv 2