|
| 1 | +/* |
| 2 | +* Task given at a state exam in Sofia university. |
| 3 | +* Rooted tree has <symbol, number> vertices. |
| 4 | +* |
| 5 | +* A path from root to a leaf can yeild a word. |
| 6 | +* Given two vertices find the sum of the numbers |
| 7 | +* of all the leaf-to-root paths with the same words. |
| 8 | +*/ |
| 9 | + |
| 10 | + |
| 11 | +#include <iostream> |
| 12 | +#include <vector> |
| 13 | +#include <string> |
| 14 | +#include <unordered_map> |
| 15 | + |
| 16 | +struct Node |
| 17 | +{ |
| 18 | + std::vector<Node*> children; |
| 19 | + int value; |
| 20 | + char symbol; |
| 21 | + |
| 22 | + Node(int n, char c) : value(n), symbol(c) {} |
| 23 | +}; |
| 24 | + |
| 25 | +using container_t = std::unordered_multimap<std::string, unsigned>; |
| 26 | + |
| 27 | +void constructWord(const Node *root, |
| 28 | + container_t &result, |
| 29 | + std::string &curentWord, |
| 30 | + unsigned number) |
| 31 | +{ |
| 32 | + if (!root) |
| 33 | + { |
| 34 | + return; |
| 35 | + } |
| 36 | + number += root->value; |
| 37 | + if (!root->children.size()) |
| 38 | + { |
| 39 | + result.insert({curentWord + root->symbol, number}); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + curentWord.push_back('\0'); |
| 44 | + |
| 45 | + for (const Node *c : root->children) |
| 46 | + { |
| 47 | + curentWord.back() = root->symbol; |
| 48 | + constructWord(c, result, curentWord, number); |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +int sumVal(const Node *u, const Node *v) |
| 53 | +{ |
| 54 | + container_t uWords; |
| 55 | + container_t vWords; |
| 56 | + |
| 57 | + std::string buff; |
| 58 | + |
| 59 | + constructWord(v, vWords, buff, 0); |
| 60 | + buff.clear(); |
| 61 | + constructWord(u, uWords, buff, 0); |
| 62 | + unsigned sum = 0; |
| 63 | + |
| 64 | + for (const auto &uWordData : uWords) |
| 65 | + { |
| 66 | + auto range = vWords.equal_range(uWordData.first); |
| 67 | + |
| 68 | + while (range.first != range.second) |
| 69 | + { |
| 70 | + sum += range.first->second + uWordData.second; |
| 71 | + ++range.first; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return sum; |
| 76 | +} |
| 77 | + |
| 78 | +void free(Node *root) |
| 79 | +{ |
| 80 | + if(!root) return; |
| 81 | + |
| 82 | + for(Node* c : root->children) |
| 83 | + { |
| 84 | + free(c); |
| 85 | + } |
| 86 | + |
| 87 | + delete root; |
| 88 | +} |
| 89 | + |
| 90 | +int main() |
| 91 | +{ |
| 92 | + Node *root = new Node(1, 'a'); |
| 93 | + root->children.push_back(new Node(2, 'b')); |
| 94 | + root->children.push_back(new Node(3, 'a')); |
| 95 | + |
| 96 | + root->children[1]->children.push_back(new Node(4, 'b')); |
| 97 | + |
| 98 | + std::cout << sumVal(root, root->children[1]); |
| 99 | + |
| 100 | + free(root); |
| 101 | +} |
0 commit comments