Cod sursa(job #2554268)

Utilizator Robys01Robert Sorete Robys01 Data 22 februarie 2020 18:50:19
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
#define NMAX 100001
using namespace std;

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

int n, nr, vf[NMAX*2], urm[NMAX*2], last[NMAX];
int lastNod, cost[NMAX];
queue < pair < int, int > > Q;

void adauga(int nod, int v)
{
    vf[++nr] = v;
    urm[nr] = last[nod];
    last[nod] = nr;

}


void citire()
{
    fin>>n;
    for(int i=1; i<n; i++)
    {
        int x, y; fin>>x>>y;
        adauga(x, y);
        adauga(y, x);
    }
}

void bfs(int Nod, int Tata)
{
    memset(cost, 0, sizeof(cost));
    Q.push( {Nod, Tata } );
    while(!Q.empty())
    {
        int nod = Q.front().first; int tata = Q.front().second;
        Q.pop();
        lastNod = nod;
        for(int k = last[nod]; k; k = urm[k])
        {
            if(vf[k] != tata)
            {
                cost[ vf[k] ] = cost[nod] + 1;
                Q.push( {vf[k], nod} );
            }
        }


    }


}

int main()
{
    citire();
    bfs(1, 0);
    bfs(lastNod, 0);
    fout<<cost[lastNod] + 1;

    return 0;
}