Cod sursa(job #2367697)

Utilizator HoratioHoratiu Duma Horatio Data 5 martie 2019 12:00:09
Problema Guvern Scor 0
Compilator cpp-64 Status done
Runda bv_11_12 Marime 2.56 kb
#include <cstdio>
#include <vector>
#include <bitset>
#include <set>
#include <queue>
#define NMAX 200005
using namespace std;

struct nod
{
    int cost;
    int indice;
    int min;
    int rg;

    bool const operator<(const nod a)const
    {
        return cost<a.cost;
    }

}N[NMAX];

vector<int> G[NMAX];
bitset<NMAX> V;

set<nod> Sir;

int n;

void citire()
{
    scanf("%d",&n);
    for(int i=0;i<n-1;i++)
    {
        int a,b;
        scanf("%d %d",&a,&b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
    for(int i=1;i<=n;i++)
    {
        N[i].indice=i;
        scanf("%d ",&N[i].cost);
        N[i].min=0;
        N[i].rg=0;
    }
}

void DFS()
{
    vector<int> Q;
    Q.push_back(1);
    while(!Q.empty())
    {
    int i=Q.back();
    Q.pop_back();

    V[i]=1;
    auto ite=Sir.upper_bound(N[i]);
    if(ite!=Sir.end())
        N[i].min=(*ite).indice;

    Sir.insert(N[i]);
    for(auto it:G[i])
    {
        if(V[it]==0)
            {
            Q.push_back(it);
            }
    }
    }
}

void BFS(int i,int k)
{
    V[i]=1;
    N[i].rg=k;
    auto ite=Sir.upper_bound(N[i]);
    if(ite!=Sir.end())
        N[i].min=(*ite).indice;

    Sir.insert(N[i]);
    for(auto it:G[i])
    {
        if(V[it]==0)
            BFS(it,k+1);
    }
    Sir.erase(N[i]);
}

void afis()
{
    for(auto it:Sir)
    {
        printf("%d %d %d\n",it.cost,it.indice,it.min);
    }
}

void DP()
{
    int lmax=0;
    V.reset();
    while(V.count()!=n)
    {
        int l=0;

        auto it=Sir.begin();

        while(V[(*it).indice])
                it++;

        while(it!=Sir.end())
        {
            l++;

            V[(*it).indice]=1;
            int rg=(*it).rg;
            int aux=(*it).min;
            //printf("%d\n",(*it).indice);

            if(aux==0)
                break;

            while((*it).indice != aux)
                {
                if((*it).min==aux && (*it).rg<=rg && V[(*it).indice]==0)
                {
                    l++;
                    V[(*it).indice]=1;
                    //printf("%d\n",(*it).indice);
                }
                it++;
                }
        }
        //printf("\n");
        if(l>lmax)
            lmax=l;
        l=0;
    }
    printf("%d",lmax);
}


int main()
{
    freopen("guvern.in","r",stdin);
    freopen("guvern.out","w",stdout);
    citire();
    BFS(1,0);
    for(int i=1;i<=n;i++)
        Sir.insert(N[i]);
    //afis();
    DP();
    return 0;
}