Cod sursa(job #1126742)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 27 februarie 2014 09:34:58
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <stack>

using namespace std;

const char infile[] = "ctc.in";
const char outfile[] = "ctc.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int oo = 0x3f3f3f3f;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

int N, M, lowLink[MAXN], deep[MAXN], idx;
Graph G;
bitset <MAXN> inSt;
stack <int> st;
set <set <int> > CTC;

void Tarjan(int Node) {
    lowLink[Node] = deep[Node] = ++ idx;
    st.push(Node);
    inSt[Node] = true;
    for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it)
        if(!deep[*it]) {
            Tarjan(*it);
            lowLink[Node] = min(lowLink[Node], lowLink[*it]);
        } else if(inSt[*it])
            lowLink[Node] = min(lowLink[Node], lowLink[*it]);
    if(deep[Node] == lowLink[Node]) {
        int nod;
        set <int> actComp;
        do {
            nod = st.top();
            st.pop();
            inSt[nod] = false;
            actComp.insert(nod);
        }while(nod != Node);
        CTC.insert(actComp);
    }
}

int main() {
    fin >> N >> M;
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
    for(int i = 1 ; i <= N ; ++ i)
        if(!deep[i])
            Tarjan(i);
    fout << CTC.size() << '\n';
    for(auto comp : CTC) {
        for(auto it : comp)
            fout << it << ' ';
        fout << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}