Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <set>
- #include <unordered_map>
- #include <string>
- #include <algorithm>
- int CalculateHeight(const std::string& name, const std::unordered_map<std::string, std::string>& tree,
- std::unordered_map<std::string, int>& heights) {
- if (heights.count(name)) {
- return heights[name];
- }
- if (!tree.count(name)) {
- return heights[name] = 0;
- }
- return heights[name] = CalculateHeight(tree.at(name), tree, heights) + 1;
- }
- int main() {
- std::unordered_map<std::string, std::string> tree;
- std::unordered_map<std::string, int> heights;
- std::set<std::string> names;
- int amount;
- std::cin >> amount;
- for (int index = 0; index + 1 < amount; ++index) {
- std::string child, parent;
- std::cin >> child >> parent;
- tree[child] = parent;
- names.insert(child);
- names.insert(parent);
- }
- for (const auto& name : names) {
- std::cout << name << " " << CalculateHeight(name, tree, heights) << "\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement