Cod sursa(job #1138974)

Utilizator UAIC_Balan_Negrus_HreapcaUAIC Balan Negrus Hreapca UAIC_Balan_Negrus_Hreapca Data 10 martie 2014 19:21:21
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.46 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iterator>
#include <random>
#include <assert.h>
using namespace std;

const string file = "ctc";

const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f; 

//#define ONLINE_JUDGE

vector<vector<int> > G;
vector<int> lowlink;
vector<int> idx;
vector<int> uz;
int contor;
vector<vector<int> > ctc;
stack<int> st;

void tarjan(int x)
{
    lowlink[x] = idx[x] = ++contor;
    st.push(x);

    for(vector<int>::iterator itr = G[x].begin();
            itr != G[x].end();
            itr++)
    {
        if(idx[*itr] == -1)
        {
            tarjan(*itr);
            lowlink[x] = min(lowlink[x], lowlink[*itr]);
        }
        else if(uz[*itr] == false)
        {
            lowlink[x] = min(lowlink[x], lowlink[*itr]);
        }
    }

    if(lowlink[x] == idx[x])
    {
        int n = -1;
        vector<int> newCtc;
        while( n != x)
        {
            n = st.top();
            st.pop();
            newCtc.push_back(n);
            uz[n] = true;
        }
        ctc.push_back(newCtc);
    }

}

int main()
{
#ifdef ONLINE_JUDGE
	ostream &fout = cout;
	istream &fin = cin;
#else
	fstream fin(infile.c_str(), ios::in);
	fstream fout(outfile.c_str(), ios::out);
#endif	

    int N, M;
    fin >> N >> M;
    
    G.resize(N + 1);
    lowlink.resize(N + 1, -1);
    idx.resize(N + 1, -1);
    uz.resize(N + 1, false);


    for(int i = 0; i < M; i++)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }

    for(int i = 1; i <= N; i++)
    {
        if(idx[i] == -1)
            tarjan(i);
    }

    fout << ctc.size() << "\n";
    for(vector<vector<int> > ::iterator itr = ctc.begin();
            itr != ctc.end();
            itr++)
    {
        copy(itr->rbegin(), itr->rend(), ostream_iterator<int>(fout, " "));
        fout << "\n";
    }

#ifdef ONLINE_JUDGE
#else
    fout.close();
	fin.close();
#endif
}