Cod sursa(job #2019672)

Utilizator antanaAntonia Boca antana Data 8 septembrie 2017 12:11:04
Problema Guvern Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 2e5 + 1;
const int INF  = 0x3f3f3f3f;

FILE *fin, *fout;

vector < int > G[MAXN];

int n, k, val[MAXN], dad[MAXN], stk[MAXN], d[MAXN], now[MAXN];
bool seen[MAXN];

class compare {
public:
    bool operator () (const int &a, const int &b) const {
        return val[ a ] < val[ b ];
    }
};

set < int, compare > srt;
set < int, compare >::iterator it;

void dfs( int node ) {
    seen[ node ] = 1;
    stk[ ++k ] = node;

    it = srt.lower_bound( node );
    if (it != srt.end())
        dad[ node ] = *it;

    srt.insert( node );

    for (int son: G[ node ])
        if (!seen[ son ])
            dfs( son );

    k--;
    srt.erase( node );
}

void compute( int node ) {
    seen[ node ] = 1;
    d[ node ] += 1;

    for (int son: G[ node ])
        if (!seen[ son ]) {
            now[ node ] = 0;
            compute( son );
            d[ node ] += now[ node ];
        }

    now[ dad[ node ] ] = max( now[ dad[ node ] ], d[ node ] );
}

int main()
{
    fin = fopen( "guvern.in", "r");
    fout= fopen( "guvern.out","w");

    int x, y;

    fscanf(fin, "%d", &n);
    for (int i = 1; i < n; i++) {
        fscanf(fin, "%d%d", &x, &y);
        G[ x ].push_back( y );
        G[ y ].push_back( x );
    }

    for (int i = 1; i <= n; i++)
        fscanf(fin, "%d", &val[ i ]);

    dfs( 1 );
    memset( seen, 0, sizeof seen );
    compute( 1 );

    int ans = 0;
    for (int i = 1; i <= n; i++)
        ans = max( ans, d[ i ] );

    fprintf(fout, "%d", ans);

    fclose( fin );
    fclose( fout );

    return 0;
}