Cod sursa(job #2819646)

Utilizator Mihai7218Bratu Mihai-Alexandru Mihai7218 Data 18 decembrie 2021 19:32:10
Problema Zvon Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.8 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
using namespace std;
ifstream fin("zvon.in");
ofstream fout("zvon.out");
int n, t, tc, x, y, i, mx;
vector <int> d;
vector <vector<int>> v, bkv;
bool comp (int a, int b)
{
    return d[a] > d[b];
}
void bfsd(int k)
{
    queue <int> q;
    q.push(k);
    vector <int> s;
    s.resize(n+1);
    s[k] = 1;
    while (!q.empty())
    {
        y = q.front();
        q.pop();
        for (x = 0; x < bkv[y].size(); x++)
        {
            if (s[bkv[y][x]] == 0)
                s[bkv[y][x]] = 1, q.push(bkv[y][x]), d[bkv[y][x]] += v[k].size();
        }
    }
}
int main()
{
    fin >> t;
    for (tc = 1; tc <= t; tc++)
    {
        fin >> n; v.resize(n+1); bkv.resize(n+1);
        for (i = 1; i < n; i++)
        {
            fin >> x >> y;
            v[x].push_back(y);
            bkv[y].push_back(x);
        }
        d.resize(n+1);
        for (i = 1; i <= n; i++)
        {
            if (v[i].size() != 0)
                bfsd(i);
            d[i]+=v[i].size();
        }
        for (i = 1; i <= n; i++)
        {
            sort (v[i].begin(), v[i].end(), comp);
        }
        queue <int> q;
        q.push(1);
        vector <int> s;
        s.resize(n+1);
        s[1] = 1;
        mx = 0;
        while (!q.empty())
        {
            y = q.front();
            q.pop();
            for (x = 0; x < v[y].size(); x++)
            {
                if (s[v[y][x]] == 0)
                    s[v[y][x]] = s[y]+x+1, q.push(v[y][x]), mx = max(mx, s[v[y][x]]);
            }
        }
        if (mx > 0)
            fout << mx-1 << "\n";
        else fout << "0\n";
        v.resize(1);
        bkv.resize(1);
        d.resize(1);
    }
    return 0;
}