Cod sursa(job #1393979)

Utilizator tudoras8tudoras8 tudoras8 Data 19 martie 2015 21:44:34
Problema Stramosi Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.84 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<vector<int>> query;
vector<pair<int, int> > queryOrder;

struct pairhash {
public:
  template <typename T, typename U>
  std::size_t operator()(const std::pair<T, U> &x) const
  {
    return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
  }
};
unordered_map<pair<int, int>, int, pairhash> sol;

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 (int p : query[u]) {
                sol[make_pair(u, p)] = path[path_top - p];
            }

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

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

    ifstream f("stramosi.in");
    freopen("stramosi.out", "w", stdout);
    f >> N >> M;

    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.push_back(a);
    }

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

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

    for (int i = 1; i <= M; i++) {
        cout << sol[queryOrder[i]] << '\n';
    }

    f.close();
    return 0;
}