Cod sursa(job #1205708)

Utilizator misinoonisim necula misino Data 7 iulie 2014 19:47:44
Problema Guvern Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.66 kb
#include<fstream>
#include<vector>
#include<set>
#include<algorithm>

#define N 200100
#define INF 0x3f3f3f3f

using namespace std;

ifstream f("guvern.in");
ofstream g("guvern.out");

int i,n,vf,x,y,k,aux,p[N],val[N],u[N],st[N],stsol[N],sol[N];

vector<int>v[N],gr[N];

set<pair<int,int> >s;

inline bool subarb(int x,int y){
    if(p[y] < p[x] && u[x] < u[y])
        return 1;
    return 0;
}

inline void dfs(int x,int tata){
    p[x] = ++ k;
    s.insert(make_pair(val[x],x));

    for(vector<int>::iterator it = v[x].begin() ; it != v[x].end() ; ++ it)
        if(*it != tata)
        dfs(*it,x);

    u[x] = ++ k;
    s.erase(make_pair(val[x],x));

    if(x)
    {
        set<pair<int,int> >::iterator it = upper_bound(s.begin(),s.end(),make_pair(val[x],x));
        gr[it->second].push_back(x);
    }

    vf = 0;
    for(vector<int>::iterator it = gr[x].begin() ; it != gr[x].end() ; ++ it)
    {
        st[++ vf] = *it;
        stsol[vf] = sol[*it];

        aux = 0;

        while(vf >= 2 && subarb(st[vf - 1],st[vf]))
        {
            aux += stsol[vf];

            st[vf - 1] = st[vf];
            stsol[vf - 1] = stsol[vf];

            --vf;
        }

        stsol[vf] = max(stsol[vf],aux);
    }

    sol[x] = 1;

    while(vf)
    {
        sol[x] += stsol[vf --];
    }
}

int main()
{
    f >> n;

    for(i = 1 ; i < n ; ++ i)
    {
        f >> x >> y;

        v[x].push_back(y);
        v[y].push_back(x);
    }

    for(i = 1 ; i <= n ; ++ i)
        f >> val[i];

    v[0].push_back(1);
    val[0] = INF;
    dfs(0,-1);

    g << sol[0] - 1 << '\n';

    return 0;
}