Cod sursa(job #1743286)

Utilizator vladtarniceruVlad Tarniceru vladtarniceru Data 17 august 2016 21:49:09
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;

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

const int MAX = 1e5 + 5;
int n;
vector<int> g[MAX];
bool vis[MAX];
int depth[MAX];
int r;

inline void dfs(const int node) {
    vis[node] = true;
    int first = 0, second = 0;
    for (auto next : g[node]) {
        if (!vis[next]) {
            dfs(next);
            if (depth[node] < depth[next] + 1) {
                depth[node] = depth[next] + 1;
            }
            if (first < depth[next]) {
                second = first;
                first = depth[next];
            } else if (second < depth[next]) {
                second = depth[next];
            }
        }
    }
    if (depth[node] == 0) {
        depth[node] = 1;
    }
    r = max(r, first + second + 1);
}

int main() {
    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);
    }
    dfs(1);
    fout << r << '\n';
    fout.close();
    return 0;
}