Cod sursa(job #2316127)

Utilizator TheNextGenerationAyy LMAO TheNextGeneration Data 11 ianuarie 2019 10:46:40
Problema Cerere Scor 5
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.54 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 1e5+1;
const int L = 20;

ifstream in("cerere.in");
ofstream out("cerere.out");

int dp[L][N],val[N],rez[N],lvl[N],lg;
bool a[N];
vector<int> v[N];

void dfs(int x, int l)
{
    lvl[x] = 1;
    for (auto it: v[x])
        if (!lvl[it])
        {
            dp[0][it] = x;
            dfs(it,l+1);
        }
}

int query(int k, int node)
{
    for (int j = lg; j>=0; j--)
        if (k-(1<<j)>0)
            node = dp[j][node];
    return dp[0][node];
}

int main()
{
    int n;
    in >> n;
    lg = log2(n)+1;
    for (int i = 1; i<=n; i++)
        in >> val[i];
    for (int i = 1; i<n; i++)
    {
        int x,y;
        in >> x >> y;
        v[x].push_back(y);
        a[y] = 1;
    }
    int root = 0;
    for (int i = 1; i<=n; i++)
        if (!a[i])
            root = i;
    dfs(root,1);
    for (int i = 1; (1<<i)<=n; i++)
        for (int j = 1; j<=n; j++)
            dp[i][j] = dp[i-1][dp[i-1][j]];
    queue<int> q;
    q.push(root);
    memset(a,0,sizeof(a));
    a[root] = 1;
    while (!q.empty())
    {
        int now = q.front();
        q.pop();
        for (auto it: v[now])
            if (!a[it])
            {
                a[it] = 1;
                q.push(it);
                if (val[it])
                {
                    int above = query(val[it],it);
                    rez[it] = rez[above]+1;
                }
            }
    }
    for (int i = 1; i<=n; i++)
        out << rez[i] << " ";
}