Cod sursa(job #1875925)

Utilizator preda.andreiPreda Andrei preda.andrei Data 11 februarie 2017 19:42:23
Problema Cerere Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.35 kb
#include <fstream>
#include <vector>

using namespace std;

struct Node
{
    int ancestor;
    int path_length;
    bool visited = false;
    vector<int> sons;
};

typedef vector<Node> Tree;

void Dfs(Tree &t, vector<int> &st, int lev, int node)
{
    st[lev] = node;
    t[node].visited = true;
    t[node].path_length = (t[node].ancestor == 0) ?
                            0 : t[st[lev - t[node].ancestor]].path_length + 1;

    for (int son : t[node].sons) {
        if (!t[son].visited) {
            Dfs(t, st, lev + 1, son);
        }
    }
}

void FindLengths(Tree &t, int root)
{
    vector<int> st(t.size());
    Dfs(t, st, 0, root);
}

int main()
{
    ifstream fin("cerere.in");
    ofstream fout("cerere.out");

    int n;
    fin >> n;

    Tree tree(n);
    for (int i = 0; i < n; ++i) {
        fin >> tree[i].ancestor;
    }

    vector<bool> is_root(n, true);
    for (int i = 1; i < n; ++i) {
        int x, y;
        fin >> x >> y;
        tree[x - 1].sons.push_back(y - 1);
        is_root[y - 1] = false;
    }

    int root = -1;
    for (int i = 0; i < n && root == -1; ++i) {
        if (is_root[i]) {
            root = i;
        }
    }

    FindLengths(tree, root);
    for (const auto &node : tree) {
        fout << node.path_length << " ";
    }
    fout << "\n";

    return 0;
}