Cod sursa(job #2722445)

Utilizator witekIani Ispas witek Data 12 martie 2021 20:50:09
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

int n, maxDist, maxNode;
vector <vector <int> > v;
vector <bool> vis;

void read() {
    f >> n;
    v = vector <vector <int> > (n + 1);
    vis = vector <bool> (n + 1);
    int x, y;
    for(int i = 1; i < n; ++i) {
        f >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
}

void dfs(int node, int k) {
    vis[node] = true;
    if(k > maxDist) {
        maxNode = node;
        maxDist = k;
    }
    for(const int& neighbour : v[node]) {
        if(!vis[neighbour])
            dfs(neighbour, k + 1);
    }
}

int main()
{
    read();
    dfs(1, 0);
    vis = vector <bool> (n + 1);
    dfs(maxNode, 0);
    g << maxDist + 1;
}