Cod sursa(job #1679937)

Utilizator y0rgEmacu Geo y0rg Data 8 aprilie 2016 13:22:21
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;

ifstream in("darb.in");
ofstream out("darb.out");
int n;
vector< vector<int> > graph;
vector<bool> visited;
vector<int> distante;

void bfs_dist(int vertex);
int find_max();

int main()
{
    in >> n;

    if (n < 2 || n > 100000)
        return 1;

    graph.resize(n);
    visited.resize(n, false);
    distante.resize(n, 1);
    int x, y;

    for (int i = 0; i < n - 1; i++) {
        in >> x >> y;
        x--;
        y--;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    in.close();

    bfs_dist(0);
    int max1 = find_max();

    for (int i = 0; i < n; i++) {
        visited[i] = false;
        distante[i] = 1;
    }

    bfs_dist(max1);
    int max2 = find_max();

    out << distante[max2];
    out.close();
    return 0;
}

void bfs_dist(int vertex)
{
    if (vertex < 0 || vertex > n - 1)
        return;

    queue<int> q;
    int element, dist;

    q.push(vertex);
    visited[vertex] = true;

    while (!q.empty()) {
        element = q.front();
        dist = distante[element] + 1;
        for (int i = 0; i < graph[element].size(); i++)
            if (!visited[graph[element][i]]) {
                q.push(graph[element][i]);
                visited[graph[element][i]] = true;
                distante[graph[element][i]] = dist;
            }
        q.pop();
    }
}

int find_max()
{
    int max = 0;
    for (int i = 1; i < n; i++)
        if (distante[max] < distante[i])
            max = i;
    return max;
}