Cod sursa(job #2664281)

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

using namespace std;

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


vector < vector <int> > g, tg;
vector <int> topoSort, SCC;
vector <bool> seen;
int V, E;
int numSCC;


void readGraph(){

    fin >> V >> E;

    g.resize(V + 1);
    tg.resize(V + 1);
    topoSort.reserve(V);
    SCC.resize(V + 1);
    seen.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, int scc){

    seen[node] = false;
    SCC[node] = scc;

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


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]])
            DFS(topoSort[idx], ++numSCC);

    int T;
    fin >> T;

    for(; T; --T){

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

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