Cod sursa(job #2321205)

Utilizator andra_moldovanAndra Moldovan andra_moldovan Data 15 ianuarie 2019 20:15:59
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

#define inf 0x3f3f3f3f
#define MAXN 100005

using namespace std;

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

int cost[MAXN];

queue <int> Q;
vector <int> graph[MAXN];

inline void Read(int &N) {
    int x, y;

    fin >> N;

    for (int i = 1; i < N; i++) {
        fin >> x >> y;

        graph[x].push_back(y);
        graph[y].push_back(x);
    }
}

inline void BFS(int node) {
    int z;

    Q.push(node);

    memset(cost, inf, sizeof(cost));
    cost[node] = 1;

    while (!Q.empty()) {
        z = Q.front();

        for (auto x : graph[z]) {
            if (cost[x] > cost[z] + 1) {
                cost[x] = cost[z] + 1;

                Q.push(x);
            }
        }

        Q.pop();
    }
}

int main () {
    int N, p;
    Read(N);

    BFS(1); p = 0; cost[0] = 0;
    for (int i = 1; i <= N; i++) {
        if (cost[i] > cost[p])
            p = i;
    }
    BFS(p); p = 0; cost[0] = 0;

    for (int i = 1; i <= N; i++) {
        if (cost[i] > cost[p])
            p = i;
    }

    fout << cost[p];

    fin.close(); fout.close(); return 0;
}