Cod sursa(job #1438986)

Utilizator eneandradaEne Oana-Andrada eneandrada Data 21 mai 2015 11:09:55
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#define MAX_N 100006

using namespace std;

vector <int> G[MAX_N], C[MAX_N];
int index_global, top, comp_conexe;
int Stack[MAX_N], index[MAX_N], lowlink[MAX_N];
bool onStack[MAX_N] = {false};

void strongconnect(int v)
{
    index[v] = index_global;
    lowlink[v] = index_global;
    index_global ++;
    Stack[++top] = v;
    onStack[v] = true;

    for(int i = 0; i < G[v].size(); i++)
    {
        if(index[G[v][i]] == -1)
        {
            strongconnect(G[v][i]);
            lowlink[v] = min(lowlink[v], lowlink[G[v][i]]);
        }
        else
            if(onStack[G[v][i]] == true)
            {
                lowlink[v] = min(lowlink[v], lowlink[G[v][i]]);
            }
    }

    if(lowlink[v] == index[v])
    {
        comp_conexe++;
        int w;
        do
        {
            w = Stack[top];
            onStack[w] = false;
            top--;
            C[comp_conexe].push_back(w);
        }while(w != v);
    }
}

int main()
{
    int N, M, i, x, y;
    freopen("ctc.in", "r", stdin);
    scanf("%d%d", &N, &M);
    memset(index, -1, sizeof(int)*(N+1));
    memset(lowlink, -1, sizeof(int)*(N+1));

    for(i = 1; i <= M; i++)
    {
        scanf("%d%d", &x, &y);
        G[x].push_back(y);
    }
    for(i = 1; i <= N; i++)
        if(index[i] == -1)
            strongconnect(i);

    freopen("ctc.out", "w", stdout);
    printf("%d\n",comp_conexe);
    for(i = 1; i <= comp_conexe; i++)
    {
        for(int j = 0; j < C[i].size(); j++)
            printf("%d ", C[i][j]);
        printf("\n");
    }
    return 0;
}