Cod sursa(job #1706087)

Utilizator preda.andreiPreda Andrei preda.andrei Data 21 mai 2016 15:18:37
Problema Zvon Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

#define N_MAX 100000

vector<int> sub[N_MAX + 1];
vector<int> activ;

bool cmpDupaSubordonati(int s1, int s2){
    return sub[s1].size() < sub[s2].size();
}

void citire(int &n, ifstream &f){
    f >> n;
    for(int i = 1; i < n; ++i){
        int x, y;
        f >> x >> y;
        sub[x].push_back(y);
    }
}

void sortareIerarhie(int n){
    for(int i = 1; i < n; ++i){
        sort(sub[i].begin(), sub[i].end(), cmpDupaSubordonati);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    ifstream fin("zvon.in");
    ofstream fout("zvon.out");

    int t;
    fin >> t;
    while(t--){
        int n;
        citire(n, fin);

        sortareIerarhie(n);

        int minute = 0;

        activ.push_back(1);
        while(!activ.empty()){
            ++minute;

            int limita = activ.size();
            for(int i = 0; i < limita; ++i){
                int index = activ[i];
                if(sub[index].size() <= 0){
                    activ.erase(activ.begin() + i);
                    --limita;
                    --i;
                }
                else{
                    activ.push_back(sub[index].back());
                    sub[index].pop_back();
                }
            }
        }

        fout << minute - 1 << "\n";


        if(t > 0){
            for(int i = 1; i < n; ++i)
                sub[i].clear();
        }
    }

    return 0;
}