Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <map>
- #include <queue>
- using namespace std;
- struct Node {
- map<char, struct Node*> next;
- int count; // в скольких словах используется этот узел
- int end; // для скольки слов символ является конечным
- };
- struct Trie {
- struct Node* root;
- void insert(string s) {
- struct Node* current = root;
- for(char c : s) {
- if(!current->next.count(c))
- current->next[c] = new Node();
- current->count++;
- current = current->next[c];
- }
- current->count++;
- current->end++;
- }
- string find(struct Node* root, int k, int & found) {
- if(root->end > 0) found += root->end;
- if(found >= k) root->end--;
- for(auto el : root->next) {
- string res = find(el.second, k, found);
- if(found >= k) {
- el.second->count--;
- return el.first + res;
- }
- }
- return "";
- }
- string get(int k) {
- int found = 0;
- return find(root, k, found);
- }
- Trie() {
- root = new Node();
- }
- };
- bool is_digit(string s) {
- for(char c : s)
- if(!isdigit(c)) return false;
- return true;
- }
- int main() {
- Trie t = Trie();
- string s;
- int k;
- cin >> k;
- while(k--) {
- cin >> s;
- if(!is_digit(s)) t.insert(s);
- else cout << '+' << t.get(stoi(s)) << endl;
- }
- struct Node* curr = t.root;
- for(char c : "badest") {
- cout << curr->count << ' ' << curr->end << endl;
- curr = curr->next[c];
- }
- cout << t.get(2) << endl;
- // curr = t.root;
- // for(char c : "badest") {
- // cout << curr->count << ' ' << curr->end << endl;
- // curr = curr->next[c];
- // }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement