Cod sursa(job #2835431)

Utilizator DMR6476Erdic Dragos DMR6476 Data 18 ianuarie 2022 18:28:37
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
vector< vector<int> > theNeighbours;
vector< vector<int> > theTransposed;
bitset< 100005> isThere;
stack<int> theStack;
bitset<100005> isOnStack;
int scc;

void dfs(int node)
{
    isThere[node] = 1;
    vector<int> ::iterator eachOne;
    for(eachOne = theNeighbours[node].begin(); eachOne != theNeighbours[node].end(); eachOne++)
    {
        int currNode = *eachOne;
        if(isThere[ currNode]== 0)
            dfs(currNode);
    }
    theStack.push(node);

}
vector<vector<int> > theComponents;
void dfs2(int node)
{
    isThere[node] = 1;
    vector<int> :: iterator eachOne;
    for(eachOne = theTransposed[node].begin(); eachOne != theTransposed[node].end(); eachOne++)
    {
        int currElem = *eachOne;
        if(isThere[currElem] == 0)
            dfs2(currElem);
    }
    theComponents[scc].push_back(node);

}

int main()
{
    int n,m;
    fin>>n>>m;
    theNeighbours = vector<vector<int> > (n+1);
    theTransposed = vector<vector<int> > (n+1);
    theComponents = vector<vector<int> > (n+1);
    for(int i = 0; i < m ; i++)
    {
        int x,y;
        fin>>x>>y;
        theNeighbours[x].push_back(y);
        theTransposed[y].push_back(x);
    }
    for(int i = 1 ; i <= n ; i++)
        if(isThere[i] == 0)
            dfs(i);
    isThere.reset();
    while(theStack.empty() == 0)
    {
        int currElem = theStack.top();
        if(isThere[currElem] == false)
        {
            ++scc;
            dfs2(currElem);
        }

        theStack.pop();
    }
    fout<<scc<<'\n';;
    vector<int> :: iterator eachOne;
    for(int i = 1 ; i <= scc; i++)
    {
        sort(theComponents[i].begin(),theComponents[i].end());
        for(eachOne = theComponents[i].begin(); eachOne != theComponents[i].end(); eachOne++)
        {
            fout<<*eachOne<<" ";
        }
        fout<<"\n";
    }

    return 0;
}