Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <vector>
- #if defined(__unix__) || defined(__APPLE__)
- #endif
- class Node;
- class Node {
- public:
- int key;
- Node *parent;
- std::vector<Node *> children;
- Node() {
- this->parent = NULL;
- }
- void setParent(Node *theParent) {
- parent = theParent;
- parent->children.push_back(this);
- }
- int height(Node node)
- {
- if (node.children.size() == 0)
- return 0;
- int maxH = 0;
- for (int i = 0; i < node.children.size(); ++i)
- {
- if (maxH < height(*node.children[i]))
- {
- maxH = height(*node.children[i]);
- }
- }
- maxH += 1;
- return maxH;
- }
- };
- int main()
- {
- std::ios_base::sync_with_stdio(0);
- int n;
- std::cin >> n;
- int root;
- std::vector<Node> nodes;
- nodes.resize(n);
- for (int child_index = 0; child_index < n; child_index++) {
- int parent_index;
- std::cin >> parent_index;
- if (parent_index >= 0)
- nodes[child_index].setParent(&nodes[parent_index]);
- else
- {
- //нужно отловить корень
- root = child_index;
- }
- nodes[child_index].key = child_index;
- }
- std::cout << nodes[root].height(nodes[root]) + 1 << std::endl;
- //for (int i =0; i < n; ++i)
- //{
- // for (int j = 0; j < nodes[i].children.size(); ++j)
- // {
- // std::cout << nodes[i].children[j];
- // }
- // std::cout << std::endl;
- //}
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement