Cod sursa(job #1116532)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 22 februarie 2014 17:37:28
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 <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; }

Graph G;
vector <set <int> > strCtc;
int deep[MAXN], lowLink[MAXN], idx, N, M;
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(deep[Node] == lowLink[Node]) {
        int prevNode;
        set <int> actCtc;
        do {
            prevNode = St.top();
            St.pop();
            inSt[prevNode] = false;
            actCtc.insert(prevNode);
        }while(prevNode != Node);
        strCtc.push_back(actCtc);
    }
}

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 << strCtc.size() << '\n';
    for(vector <set<int> > :: iterator it = strCtc.begin(), fin = strCtc.end() ; it != fin ; ++ it, fout << '\n')
        for(set <int> :: iterator i = it->begin(), j = it->end() ; i != j ; ++ i)
            fout << *i << ' ';
    fin.close();
    fout.close();
    return 0;
}