Cod sursa(job #2721547)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 11 martie 2021 22:39:16
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

ifstream fin("darb.in");
ofstream fout("darb.out");

const int NMax = 1e5;

vector <int> g[NMax + 5];

int n, maxdistance, maxnode;
int dist[NMax + 5];

void Read(){
    fin >> n;
    for (int i = 1; i <= n; i++){
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
}

void DFS(int node){
    if (dist[node] > maxdistance){
        maxdistance = dist[node];
        maxnode = node;
    }
    for (auto ngh : g[node])
        if (!dist[ngh]){
            dist[ngh] = dist[node] + 1;
            DFS(ngh);
        }
}

void Reset(){
    memset(dist, 0, sizeof dist);
    maxdistance = 0;
    dist[maxnode] = 1;
}

void Solve(){
    dist[1] = 1;
    DFS(1);
    Reset();
    DFS(maxnode);
}

void Print(){
    fout << maxdistance << '\n';
}

int main(){
    Read();
    Solve();
    Print();
    return 0;
}