Cod sursa(job #102344)

Utilizator scvalexAlexandru Scvortov scvalex Data 14 noiembrie 2007 12:07:05
Problema Zvon Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.32 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

class Nod;

class Pair {
public:
	Pair(int _car, Nod* _cdr) :
		car(_car),
		cdr(_cdr)
	{
	}

	int car;
	Nod *cdr;
};

class Nod {
public:
	Nod(int _n) :
		n(_n),
		p(0) {
	}
	
	int n, p;
	vector< Nod * > c;
};

int n;
vector<Nod> noduri;

bool cmp(const Pair &a, const Pair &b) {
	return a.car > b.car;
}

void calculeaza_prioritati(Nod *n) {
	int p(0);
	
	vector<Pair> temp;
	for (int i(0); i < (int)n->c.size(); ++i) {
		calculeaza_prioritati(n->c[i]);
		p += n->c[i]->p;
		temp.push_back(Pair(n->c[i]->p, n->c[i]));
	}
	p += n->c.size();
	
	sort(temp.begin(), temp.end(), cmp);
	for (int i(0); i < (int)n->c.size(); ++i)
		n->c[i] = temp[i].cdr;
	
	n->p = p;
}

int main(int argc, char *argv[]) {
	ifstream fin("zvon.in");
	int T;
	fin >> T;
	
	ofstream fout("zvon.out");
	for (int t(0); t < T; ++t) {
		fin >> n;
		noduri.clear();
		for (int i(0); i < n; ++i)
			noduri.push_back(Nod(i + 1));
		int a, b;
		for (int i(0); i < n - 1; ++i) {
			fin >> a >> b;
			noduri[a - 1].c.push_back(&noduri[b - 1]);
		}
		
		calculeaza_prioritati(&noduri[0]);
		
		//for (int i(0); i < (int)noduri.size(); ++i)
		//	cout << i << ": " << noduri[i].p << endl;
		
		vector< Nod* > cur;
		vector<bool> vizitat(n, false);
		int vizitate(1);
		int t(0);
		cur.push_back(&noduri[0]);
		vector<bool> terminat(n, false);
		while (vizitate < n) {
			//cout << "T=" << t << ": " << endl;
			int temp = cur.size();
			for (int i(0); i < temp; ++i) {
				if (terminat[cur[i]->n])
					continue;
				int max(-1);
				/*for (int j(0); j < (int)cur[i]->c.size(); ++j)
					if ((!vizitat[cur[i]->c[j]->n]) && ((max == -1) || (cur[i]->c[j]->p > cur[i]->c[max]->p)))
						max = j;*/
				if (cur[i]->c.size() > 0)
					max = 0;
				if (max != -1) {
					vizitat[cur[i]->c[max]->n] = true;
					//cout << "Vizitez: " << cur[i]->c[max]->n << endl;
					cur.push_back(cur[i]->c[max]);
					//cout << cur[i]->c.size() << endl;
					cur[i]->c.erase(cur[i]->c.begin());
					//cout << cur[i]->c.size() << endl;
					++vizitate;
					//cout << vizitate << endl;
				} else
					terminat[cur[i]->n] = true;
			}
			++t;
		}
		fout << t << endl;
	}
	fout.close();
	
	fin.close();
	
	return 0;
}