Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- struct Node {
- int Parent = 0;
- std::vector<int> Children;
- int Height = 0;
- };
- void DFS(int v, std::vector<Node>& tree) {
- for (int u : tree[v].Children) {
- DFS(u, tree);
- tree[v].Height = std::max(tree[v].Height, tree[u].Height + 1);
- }
- }
- int Diametr(std::vector<Node>& tree) {
- int result = 0;
- for (int i = 0; i < tree.size(); ++i) {
- if (tree[i].Children.empty()) continue;
- if (tree[i].Children.size() == 1) {
- result = std::max(result, tree[i].Height);
- } else {
- std::pair<int, int> best = {tree[tree[i].Children[0]].Height, tree[tree[i].Children[1]].Height};
- if (best.first > best.second) std::swap(best.first, best.second);
- for (int j = 2; j < tree[i].Children.size(); ++j) {
- if (tree[tree[i].Children[j]].Height >= best.second) {
- best.first = best.second;
- best.second = tree[tree[i].Children[j]].Height;
- } else if (tree[tree[i].Children[j]].Height >= best.first) {
- best.first = tree[tree[i].Children[j]].Height;
- }
- }
- result = std::max(result, best.first + best.second + 2);
- }
- }
- return result;
- }
- int main() {
- int n = 0; std::cin >> n;
- std::vector<Node> tree(n);
- for (int i = 0; i < n - 1; ++i) {
- int a, b; std::cin >> a >> b;
- if (a > b) std::swap(a, b);
- tree[b].Parent = a;
- tree[a].Children.push_back(b);
- }
- DFS(0, tree);
- for (int i = 0; i < n; ++i) {
- std::cout << i << ": [Height=" << tree[i].Height << "], [Children=";
- for (int& x : tree[i].Children) std::cout << x << ",";
- std::cout << "]\n";
- }
- std::cout << Diametr(tree);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement