Cod sursa(job #1160692)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 30 martie 2014 18:34:54
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.56 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 <deque>

using namespace std;

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

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; }

Graph G, Gt;
int N, M;
bitset <MAXN> Used;
vector <int> tsort;
vector <vector <int> > CTC;
vector <int> act;

inline void DFs(int Node) {
    Used[Node] = 1;
    for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it)
        if(!Used[*it])
            DFs(*it);
    tsort.push_back(Node);
}

inline void DFs2(int Node) {
    Used[Node] = 0;
    act.push_back(Node);
    for(It it = Gt[Node].begin(), fin = Gt[Node].end(); it != fin ; ++ it)
        if(Used[*it])
            DFs2(*it);
}

inline void Kosaraju() {
    for(int i = 1 ; i <= N ; ++ i)
        if(!Used[i])
            DFs(i);
    for(vector <int> :: reverse_iterator it = tsort.rbegin(), fin = tsort.rend(); it != fin ; ++ it)
        if(Used[*it]) {
            DFs2(*it);
            CTC.push_back(act);
            vector <int> ().swap(act);
        }
    fout << CTC.size() << '\n';
    for(auto comp : CTC) {
        for(auto it : comp)
            fout << it << ' ';
        fout << '\n';
    }
}

const int lim = (1 << 20);
char buff[lim];
int pos;

inline void get(int &x) {
    x = 0;
    while(!('0' <= buff[pos] && buff[pos] <= '9'))
        if(++ pos == lim) {
            fread(buff, 1, lim, stdin);
            pos = 0;
        }
    while('0' <= buff[pos] && buff[pos] <= '9') {
        x = x * 10 + buff[pos] - '0';
        if(++ pos == lim) {
            fread(buff, 1, lim, stdin);
            pos = 0;
        }
    }
}

int main() {
    freopen(infile, "r", stdin);
    get(N);
    get(M);
    for(int i = 0 ; i < M ; ++ i) {
        int x, y;
        get(x); get(y);
        G[x].push_back(y);
        Gt[y].push_back(x);
    }
    Kosaraju();
    fout.close();
    return 0;
}