Cod sursa(job #1214579)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 30 iulie 2014 20:28:31
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 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";

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

Graph G, Gt;
int n, m;
vector <vector <int> > CTC;
vector <int> discovered;
bitset <MAXN> used;
vector <int> act;

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);
    discovered.push_back(node);
}

void dfsback(int node) {
    used[node] = 0;
    act.push_back(node);
    for(It it = Gt[node].begin(); it != Gt[node].end() ; ++ it)
        if(used[*it])
            dfsback(*it);
}

int main() {
    cin.sync_with_stdio(false);
    #ifndef ONLINE_JUDGE
    freopen(infile, "r", stdin);
    freopen(outfile, "w", stdout);
    #endif
    fin >> n >> m;
    for(int i = 1 ; i <= m ; ++ i) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
        Gt[y].push_back(x);
    }
    for(int i = 1 ; i <= n ; ++ i)
        if(!used[i])
            dfs(i);
    for(auto it = discovered.rbegin() ; it != discovered.rend() ; ++ it)
        if(used[*it]) {
            vector <int> ().swap(act);
            dfsback(*it);
            CTC.push_back(act);
        }
    fout << CTC.size() << '\n';
    for(auto comp = CTC.begin() ; comp != CTC.end(); ++ comp, fout << '\n')
        for(auto it = comp->begin() ; it != comp->end() ; ++ it)
            fout << *it << ' ';
    fin.close();
    fout.close();
    return 0;
}