Cod sursa(job #1506393)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 20 octombrie 2015 16:32:30
Problema Guvern Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.04 kb
#include <fstream>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <utility>
#include <tuple>
using namespace std;

constexpr int unvisited = -1;
constexpr int nmax = 200001;

array<vector<int>, nmax> graf;
array<int, nmax> coop, best_subarb, best_upto_begin;
array<vector<int>, nmax> fortat_de;
auto cmp = [](const int x, const int y){
	return coop[x] < coop[y]; };
set<int, decltype(cmp)> parinti(cmp);
array<pair<int, int>, nmax> st_fin;
int poz_euler = 0;

void dfs(const int cur, const int prev){
	/*
	cout << cur << " - ";
	for(const auto x : parinti){
		cout << x << ' '; }
	cout << endl;
	*/

	if(!parinti.empty()){
		fortat_de[*parinti.lower_bound(cur)].push_back(cur); }

	st_fin[cur].first = poz_euler++;

	parinti.insert(cur);
	for(const auto next : graf[cur]){
		if(next != prev){
			dfs(next, cur); } }
	parinti.erase(cur);

	st_fin[cur].second = poz_euler++;
	vector<pair<int, int>> evenimente;
	for(const auto x : fortat_de[cur]){
		evenimente.emplace_back(x, st_fin[x].first);
		evenimente.emplace_back(x, st_fin[x].second); }
	sort(begin(evenimente), end(evenimente),
		[](const pair<int, int>& a, const pair<int, int>& b){
			return a.second < b.second; });
	int best_here = 1;
	for(const auto x : evenimente){
		if(best_upto_begin[x.first] == unvisited){
			//echivalent cu x e un inceput
			best_upto_begin[x.first] = best_here; }
		else{
			best_here = max(best_upto_begin[x.first] + best_subarb[x.first],
				best_here); } }
	best_subarb[cur] = best_here; }

int main(){
	ifstream f("guvern.in");
	ofstream g("guvern.out");
	int n;
	f >> n;
	for(int i = 0, a, b; i < n-1; ++i){
		f >> a >> b;
		graf[a].push_back(b);
		graf[b].push_back(a); }
	graf[0].push_back(1);
	graf[1].push_back(0);
	coop[0] = 1000000001;
	for(int i = 1; i <= n; ++i){
		f >> coop[i]; }
	for(int i = 0; i <= n; ++i){
		best_upto_begin[i] = unvisited; }

	dfs(0, -1);

	/*
	for(int i = 0; i <= n; ++i){
		cout << i << " - ";
		for(const auto x : fortat_de[i]){
			cout << x << ' '; }
		cout << endl; }
	cout << endl;
	*/

	g << best_subarb[0]-1;
	return 0; }