Cod sursa(job #657122)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 5 ianuarie 2012 19:59:42
Problema Guvern Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.96 kb
#include <cstdio>
#include <vector>
#include <set>
#include <stack>
#include <algorithm>

#define NMax 200005
#define Infinity 2000000000
#define v first
#define x second

using namespace std;

vector <int> G[NMax], Sons[NMax];
set < pair <int, int> > Path;
int N, Value[NMax], Start[NMax], End[NMax], Index, DP[NMax], Solution;

void SolveX (int X)
{
    stack <int> Stack, StackDP;
    for (unsigned i=0; i<Sons[X].size (); ++i)
    {
        int V=Sons[X][i], SonsDP=0;
        while (!Stack.empty () and Start[X]<=Start[Stack.top ()] and End[Stack.top ()]<=End[X])
        {
            SonsDP+=StackDP.top ();
            Stack.pop (); StackDP.pop ();
        }
        Stack.push (V);
        StackDP.push (max (SonsDP, DP[V]));
    }
    while (!Stack.empty ())
    {
        DP[X]+=StackDP.top ();
        Stack.pop (); StackDP.pop ();
    }
    ++DP[X];
    Solution=max (Solution, DP[X]);
}

void DFS (int X, int F)
{
    Start[X]=++Index;
    Path.insert (make_pair (Value[X], X));
    for (vector <int> :: iterator V=G[X].begin (); V!=G[X].end (); ++V)
    {
        if (*V!=F)
        {
            DFS (*V, X);
        }
    }
    End[X]=Index;
    Path.erase (make_pair (Value[X], X));
    set< pair <int, int> >::iterator Father=Path.lower_bound (make_pair (Value[X], 0));
    if (Father!=Path.end ())
    {
        Sons[Father->x].push_back (X);
    }
    SolveX (X);
}

void Read ()
{
    freopen ("guvern.in", "r", stdin);
    scanf ("%d", &N);
    for (int i=2; i<=N; ++i)
    {
        int X, Y;
        scanf ("%d %d", &X, &Y);
        G[X].push_back (Y);
        G[Y].push_back (X);
    }
    for (int i=1; i<=N; ++i)
    {
        scanf ("%d", &Value[i]);
    }
    G[0].push_back (1);
    Value[0]=Infinity;
}

void Print ()
{
    freopen ("guvern.out", "w", stdout);
    --Solution;
    printf ("%d\n", Solution);
}

int main()
{
    Read ();
    DFS (0, 0);
    Print ();
    return 0;
}