Cod sursa(job #1799635)

Utilizator ajeccAjechiloae Eugen ajecc Data 6 noiembrie 2016 16:20:17
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <bits/stdc++.h>
#define for0(i, n) for(int i = 0; i < n; i++)
#define for1(i, n) for(int i = 1; i <= n; i++)
#define pb push_back
#define mp make_pair
#define all(v) v.begin(), v.end()
#define V vector<int>
#define VP vector<pair<int, int> >
#define clr(A, x) memset(A, x, sizeof(A))
#define cpy(A, B) memcpy(A, B, sizeof(B))
#define g(s) getline(cin, s) ///ai grija la fin/cin ///
#define FASTIO ios_base::sync_with_stdio(0)
const long long INFLL = (1LL<<62);
const int INFINT = 2000000000;
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
/*template <typename T>
string to_string(const T& n){
    ostringstream os;
    os << n;
    return os.str();
}
*/
/*void invers_modular(int a, int b, int &d, int &x, int &y)
{
    if(!b)
    {
        d=a;
        x=1;
        y=0;
        return ;
    }
    int x0, y0;
    invers_modular(b, a%b, d, x0, y0);
    x=y0;
    y=x0-a/b*y0;
}*/ // daca x<0 se aduna cu mod pana e mai mare, x fiind rezultatul

/*ull putere(ull baza, ull exponent, ull MOD)
{
    if(exponent == 0) return 1;
    if(exponent % 2 == 0) return putere((baza * baza) % MOD, exponent / 2, MOD) % MOD;
    return ((baza % MOD) * (putere(baza, exponent - 1, MOD) % MOD) % MOD);
}*/
ifstream fin("darb.in"); /// modifica cu numele corespunzator
ofstream fout("darb.out"); /// modifica cu numele corespunzator

const int NMAX = 1e5 + 1;

int n;
V arbore[NMAX];
int frunza, sol;
bool trecut1[NMAX];
bool trecut2[NMAX];

void bfs()
{
    queue<int> coada;
    coada.push(1);

    while(!coada.empty())
    {
        int nod = coada.front();
        coada.pop();
        frunza = nod;
        trecut1[nod] = 1;
        for(auto i: arbore[nod])
            if(!trecut1[i])
                coada.push(i);
    }
}

void dfs(int nod, int dist)
{
    sol = max(sol, dist);
    trecut2[nod] = 1;
    for(auto i: arbore[nod])
        if(!trecut2[i])
            dfs(i, dist + 1);
}

int main()
{
    fin >> n;
    for1(i, n - 1)
    {
        int a, b;
        fin >> a >> b;
        arbore[a].pb(b);
        arbore[b].pb(a);
    }
    bfs();
    dfs(frunza, 1);
    fout << sol;

    return 0;
}