Cod sursa(job #2788879)

Utilizator guzgandemunteIonescu Laura guzgandemunte Data 26 octombrie 2021 16:53:31
Problema Diametrul unui arbore Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define VMAX 100001

using namespace std;

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

vector <int> adj[VMAX];
int d[VMAX];
int V, x, y;

int furthestNode(int starting_point)
{
    int u, last = starting_point;
    queue <int> q;
    for (int i = 1; i <= V; ++i) d[i] = 0;
    q.push(starting_point);
    d[starting_point] = 1;

    while (!q.empty())
    {
        u = q.front(), q.pop();
        for (int w:adj[u])
            if (!d[w])
            {
                d[w] = d[u] + 1;
                last = w;
                q.push(w);
            }
    }

    return last;
}

int main()
{
    fin >> V;

    for (int i = 0; i < V - 1; ++i)
    {
        fin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    int furthest_from_origin = furthestNode(1);
    fout << d[furthestNode(furthest_from_origin)];

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