Cod sursa(job #2984476)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 24 februarie 2023 11:45:01
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream cin("darb.in");
ofstream cout("darb.out");

int n , x , y;

const int MAX = 1e5 + 1;

bool viz[MAX];

int dist[MAX];

vector <int> g[MAX];

int main(){

    cin >> n;

    for(int i = 1 ; i < n ; i++){

        cin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    queue <int> q;

    q.push(1);

    int last;

    while(!q.empty()){

        x = q.front();
        q.pop();

        viz[x] = 1;

        last = x;

        for(auto it : g[x]){

            if(!viz[it]){

                q.push(it);
            }
        }
    }

    q.push(last);

    int maxdist = -1;

    dist[last] = 1;

    while(!q.empty()){

        x = q.front();

        q.pop();

        maxdist = max(maxdist,dist[x]);

        for(auto it : g[x]){

            if(!dist[it]){

                dist[it] = dist[x] + 1;

                q.push(it);
            }
        }
    }

    cout << maxdist;

    return 0;
}