Cod sursa(job #2799197)

Utilizator DayanamdrMardari Dayana Raluca Dayanamdr Data 12 noiembrie 2021 17:04:14
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <vector>
#include <utility>
#include <fstream>
using namespace std;

ifstream f("darb.in");
ofstream g("darb.out");

int n;

struct node {
    bool visited = false;
    vector<int> adjacentNodes; // there will be stored maximum 3 nodes (2 children, 1 parent)
} nodes[100001];

void getLongestDiameter(int current_node, int distance, pair<int, int> &furthestLeaf) {
    if (distance > furthestLeaf.second) { // update the furthest node
        furthestLeaf.first = current_node;
        furthestLeaf.second = distance;
    }
    nodes[current_node].visited = true;
    for (auto child: nodes[current_node].adjacentNodes) {
        if (nodes[child].visited == false) {
            getLongestDiameter(child, distance + 1, furthestLeaf);
        }
    }
}

int main() {
    f >> n;
    for (int i = 1; i < n; ++i) {
        int x, y;
        f >> x >> y;
        nodes[x].adjacentNodes.push_back(y);
        nodes[y].adjacentNodes.push_back(x);
    }
    pair<int, int> furthestLeaf (1, 1); // first element denotes the node, the second element denotes the distance
    getLongestDiameter(furthestLeaf.first, 1, furthestLeaf);
    for (int i = 1; i <= n; ++i) { // clean the visited status variable for each node
        nodes[i].visited = false;
    }
    getLongestDiameter(furthestLeaf.first, 1, furthestLeaf);
    g << furthestLeaf.second << "\n";
    return 0;
}