-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
80 lines (73 loc) · 1.84 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include<bits/stdc++.h>
using namespace std;
// https://www.hackerearth.com/practice/data-structures/advanced-data-structures/trie-keyword-tree/practice-problems/algorithm/registration-system/description/
class Node{
public:
unordered_map<char,Node*> children;
bool end;
int wt;
Node(){
end=false;
wt=-1;
}
};
void insert(Node* root,string word){
Node* current = root;
for(int i=0;i<word.size();i++){
char ch = word[i];
Node* node = current->children[ch];
if(node==NULL){
node = new Node();
current->children[ch]=node;
}
current=node;
}
current->end=true;
}
void update(Node* root,string word,int w){
Node* current = root;
for(int i=0;i<word.size();i++){
char ch = word[i];
Node* node = current->children[ch];
current=node;
}
current->end=true;
current->wt=w;
}
int search(Node* root,string word){
Node* current = root;
for(int i=0;i<word.size();i++){
char ch = word[i];
Node* node = current->children[ch];
if(node==NULL){
return INT_MIN;
}
current=node;
}
if(current->end) return current->wt;
else return INT_MIN;
}
int main(){
Node* root = new Node();
int n; cin>>n;
string s;
while(n--){
cin>>s;
int x = search(root,s),y;
y=x;
if(x==INT_MIN){
insert(root,s);
cout<<s<<"\n";
}
else{
string s1;
while(y!=INT_MIN){ // while already exist such username
s1 = s + to_string(++x);
y = search(root,s1);
}
insert(root,s1);
update(root,s,x);
cout<<s1<<"\n";
}
}
}