Cod sursa(job #2664450)

Utilizator DawlauAndrei Blahovici Dawlau Data 28 octombrie 2020 17:51:29
Problema Obiective Scor 5
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.36 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("obiective.in");
ofstream fout("obiective.out");


vector < vector <int> > g, tg, SCCs;
vector < set <int> > mg; // meta graph
vector <int> topoSort, SCC, depth;
vector <bool> seen;
int V, E;
int numSCC;


void readGraph(){

    fin >> V >> E;

    g.resize(V + 1);
    tg.resize(V + 1);
    topoSort.reserve(V);
    SCCs.reserve(V);
    SCC.resize(V + 1);
    seen.resize(V + 1);
    depth.resize(V + 1);

    for(int e = 0; e < E; ++e){

        int from, to;
        fin >> from >> to;

        g[from].push_back(to);
        tg[to].push_back(from);
    }
}


void topologicalSort(int node){

    seen[node] = true;

    for(const int &adj : g[node])
        if(!seen[adj])
            topologicalSort(adj);

    topoSort.push_back(node);
}


void DFS(int node, vector <int> &component){

    seen[node] = false;
    SCC[node] = numSCC;
    component.push_back(node);

    for(const int &adj : tg[node])
        if(seen[adj])
            DFS(adj, component);
}


void build_mg(){

    mg.resize(numSCC + 1);

    for(int scc = 0; scc < numSCC; ++scc)
        for(int &node : SCCs[scc])
            for(int &adj : g[node])
                if(SCC[node] != SCC[adj])
                    mg[scc + 1].insert(SCC[adj] + 1);
}


int getDistance(const int &a, const int &b){

    deque <int> Queue;
    Queue.push_back(a);

    vector <int> dist;
    dist.resize(mg.size() + 1);
    dist[a] = 1;

    while(!Queue.empty()){

        int node = Queue.front();
        Queue.pop_front();

        for(const int &adj : mg[node])
            if(dist[adj] == 0 and adj <= b){

                dist[adj] = dist[node] + 1;
                Queue.push_back(adj);
            }
    }

    return dist[b] - 1;
}


int main(){

    readGraph();

    for(int node = 1; node <= V; ++node)
        if(!seen[node])
            topologicalSort(node);

    for(int idx = V - 1; idx >= 0; --idx)
        if(seen[topoSort[idx]]){

            vector <int> component;
            component.reserve(V);

            DFS(topoSort[idx], component);
            SCCs.push_back(component);

            ++numSCC;
        }

    build_mg();

    int T;
    fin >> T;

    for(; T; --T){

        int a, b;
        fin >> a >> b;

        if(SCC[a] <= SCC[b])
            fout << 0 << '\n';
        else{

            fout << getDistance(SCC[b] + 1, SCC[a] + 1) << '\n';
        }
    }
}