Cod sursa(job #1394558)

Utilizator tudoras8tudoras8 tudoras8 Data 20 martie 2015 13:42:24
Problema Stramosi Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <map>
#include <unordered_map>

using namespace std;

const int MAXN = 250010, MAXM = 300010;

enum {
    WHITE, GRAY, BLACK
};

int N, M;
vector<int> T[MAXN], roots;
int state[MAXN];

vector<pair<int, int>> query[MAXN];
int sol[MAXN];

void dfs(int source) {
    int st[MAXN], path[MAXN], st_top = 0, path_top = 0;
    st[++st_top] = source, state[source] = GRAY;

    while (st_top > 0) {
        while (state[st[st_top]] == BLACK) {
            st_top--;
            path_top--;
        }
        if (st_top > 0) {
            int u = st[st_top];
            state[u] = BLACK;
            path[++path_top] = u;

            for (pair<int, int> p : query[u]) {
                sol[p.second] = path[path_top - p.first];
            }

            for (int v : T[u]) {
                if (state[v] == WHITE) {
                    st[++st_top] = v;
                }
            }
        }
    }
}

int main()
{
    int t, Q, P;

    //cerr.sync_with_stdio(false);
    ifstream f("stramosi.in");
    ofstream g("stramosi.out");
    f >> N >> M;

    query[0].push_back(make_pair(0, 0));
    for (int i = 1; i <= N; i++) {
        f >> t;

        if (t == 0) roots.push_back(i);
        else T[t].push_back(i);

        vector<int> a;
        //query[i].push_back(make_pair(0, 0));
    }

    for (int i = 0; i < M; i++) {
        f >> P >> Q;
        query[P].push_back(make_pair(Q, i + 1));
    }

    for (int x : roots) {
        dfs(x);
    }

    for (int i = 1; i <= M; i++) {
        g << sol[i] << '\n';
        //cerr << sol[i] << '\n';
    }

    f.close();
    return 0;
}