Cod sursa(job #2972272)

Utilizator sandry24Grosu Alexandru sandry24 Data 28 ianuarie 2023 22:38:48
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pb push_back
#define mp make_pair
#define f first
#define s second

vector<vi> adj(100005);
vector<bool> visited(100005);
int maxe = 0, maxnod;

void dfs(int x, int last_dist){
    last_dist++;
    //cout << x << ' ' << last_dist << '\n';
    visited[x] = 1;
    if(last_dist > maxe){
        maxnod = x;
        maxe = last_dist;
    }
    for(auto i : adj[x]){
        if(!visited[i]){
            dfs(i, last_dist);
        }
    }
}

void solve(){
    int n;
    cin >> n;
    for(int i = 0; i < n-1; i++){
        int a, b;
        cin >> a >> b;
        adj[a].pb(b);
        adj[b].pb(a);
    }
    dfs(1, 1);
    visited = vector<bool>(100005);
    maxe = 0;
    dfs(maxnod, 0);
    cout << maxe << '\n';
}  
 
int main(){
    freopen("darb.in", "r", stdin);
    freopen("darb.out", "w", stdout);
    ios::sync_with_stdio(0); cin.tie(0);
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
}