Cod sursa(job #2283226)

Utilizator TooHappyMarchitan Teodor TooHappy Data 15 noiembrie 2018 10:44:53
Problema Cerere Scor 15
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.66 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream in("cerere.in");
ofstream out("cerere.out");

const int Nmax = 1e5;
const int inf = 1e9;

int n;
vector< int > v, ans;
vector< bool > viz;
vector< vector < int > > G, stramos(18, vector< int >(Nmax + 5));

void DFS(int node) {
    viz[node] = true;

    for(auto vecin: G[node]) {
        if(!viz[vecin]) {
            if(v[vecin] == 0) {
                ans[vecin] = 0;
                DFS(vecin);
            } else {
                int q = vecin;
                int p = v[vecin];

                for(int i = 0; (1 << i) <= n && q; ++i) {
                    if((p >> i) % 2 == 1) {
                        q = stramos[i][q];
                    }
                }

                ans[vecin] = min(ans[vecin], ans[q] + 1);
                DFS(vecin);
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);
 
    in >> n;

    v.resize(n + 1); ans.resize(n + 1, inf); viz.resize(n + 1); G.resize(n + 1, vector< int >());
    for(int i = 1; i <= n; ++i) {
        in >> v[i];
        
        if(v[i] == 0) {
            ans[i] = 0;
        }
    }

    for(int i = 1; i < n; ++i) {
        int a, b; in >> a >> b;
        stramos[0][b] = a;
        G[a].push_back(b);
    }

    for(int i = 1; (1 << i) <= n; ++i) {
        for(int j = 1; j <= n; ++j) {
            stramos[i][j] = stramos[i - 1][stramos[i - 1][j]];
        }
    }

    for(int i = 1; i <= n; ++i) {
        if(v[i] == 0) {
            DFS(i);
            break;
        } 
    }

    for(int i = 1; i <= n; ++i) {
        out << ans[i] << " ";
    }
    out << "\n";

    in.close(); out.close();
 
    return 0;
}