Cod sursa(job #2644430)

Utilizator cyg_dawidDavid Ghiberdic cyg_dawid Data 24 august 2020 16:30:28
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

const int NMAX = 100005;
int v[NMAX], vbfs[NMAX];
int n, lmax = -1;
int indmax;

struct ELEM {
    vector <int> a2;
};
ELEM a[NMAX];

queue <int> q;

void calcBFS() {
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        for(int i = 1; i <= a[x].a2[0]; i++) {
            int k = a[x].a2[i];
            if(vbfs[k] == 0 || vbfs[k] > vbfs[x] + 1) {
                q.push(k);
                vbfs[k] = vbfs[x] + 1;
            }
        }
    }
}

int main()
{
    fin >> n;
    v[1] = 1;
    for(int i = 1; i <= n; i++) {
        a[i].a2.push_back(0);
    }
    for(int i = 1; i <= n; i++) {
        int x, y;
        fin >> x >> y;
        a[x].a2.push_back(y);
        a[x].a2[0]++;
        a[y].a2.push_back(x);
        a[y].a2[0]++;
        v[y] = v[x] + 1;
        if(v[y] > lmax) {
            lmax = v[y];
            indmax = y;
        }
    }
    q.push(indmax);
    vbfs[indmax] = 1;
    calcBFS();
    lmax = -1;
    for(int i = 1; i <= n; i++) {
        if(vbfs[i] > lmax)
            lmax = vbfs[i];
    }
    fout << lmax;
    return 0;
}