Cod sursa(job #1123127)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 25 februarie 2014 22:50:41
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.14 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; }

/// Tarjan : O(N + M)

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

void Tarjan(int Node) {
    deep[Node] = lowLink[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(lowLink[Node] == deep[Node]) {
        int temp;
        set <int> actComp;
        do {
            temp = st.top();
            st.pop();
            inSt[temp] = false;
            actComp.insert(temp);
        } while(temp != Node);
        CTC.insert(actComp);
    }
}

int main() {
    int N, M;
    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);
    /// Cool C++ 11
    fout << CTC.size() << '\n';
    for(auto comp : CTC) {
        for(auto it : comp)
            fout << it << ' ';
        fout << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}