Cod sursa(job #789662)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 18 septembrie 2012 20:38:23
Problema Guvern Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.6 kb
#include<stdio.h>
#include<vector>
#include<set>
#include<stack>

#define maxn 200005
#define pb push_back
#define mp make_pair

using namespace std;

FILE*f=fopen("guvern.in","r");
FILE*g=fopen("guvern.out","w");

int n,index;
int viz[maxn],v[maxn],D[maxn],first[maxn],last[maxn];
vector<int>G[maxn],super_sons[maxn];
set< pair<int,int> >drum;
stack< pair<int,int> >st;

inline void dinamica ( int nod ){
	
	if ( nod == 7 ){
		int u;
		++u;
	}
	
	for ( vector<int>::iterator itt = super_sons[nod].begin() ; itt != super_sons[nod].end() ; ++itt ){
		int fiu = (*itt),tobeerased = 0;
		
		while ( !st.empty() && first[fiu] < first[st.top().first] && first[st.top().first] <= last[fiu] ){
			tobeerased += st.top().second;
			st.pop();
		}
		st.push( mp(fiu,max(D[fiu],tobeerased)) );
	}
	
	D[nod] = 1;
	while ( !st.empty() ){
		D[nod] += st.top().second;
		st.pop();
	}
}

void dfs ( int nod ){
	viz[nod] = 1; first[nod] = ++index;
	drum.insert( mp(v[nod],nod) );
	
	for ( vector<int>::iterator itt = G[nod].begin() ; itt != G[nod].end() ; ++itt ){
		int nodvcn = (*itt);
		if ( !viz[nodvcn] ){
			dfs(nodvcn);
		}
	}
	
	drum.erase( mp(v[nod],nod) ); last[nod] = index;
	set< pair<int,int> >::iterator itt = drum.lower_bound( mp(v[nod],0) );
	if ( itt != drum.end() ){
		super_sons[ itt->second ].pb(nod);
	}
	
	dinamica(nod);
}

int main () {
	
	fscanf(f,"%d",&n);
	int x,y;
	for ( int i = 1 ; i < n ; ++i ){
		fscanf(f,"%d %d",&x,&y);
		G[x].pb(y); G[y].pb(x);
	}
	for ( int i = 1 ; i <= n ; ++i ){
		fscanf(f,"%d",&v[i]);
	}
	G[0].pb(1); v[0] = 1000000001;
	
	dfs(0);
	fprintf(g,"%d\n",D[0]-1);
	
	fclose(f);
	fclose(g);
	
	return 0;
}