Cod sursa(job #1774355)

Utilizator tudorgalatanRoman Tudor tudorgalatan Data 8 octombrie 2016 20:25:41
Problema Componente tare conexe Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <vector>

using namespace std;

void DFS (unsigned int node);
void DFST (unsigned int node);

unsigned int N, M;
unsigned int x, y;

vector < unsigned int > G[100001], GT[100001];
bool seen[100001];
unsigned int postorder[100001];
unsigned int i, j, k;

unsigned int no;
vector < unsigned int > sol[100001];

int main ()
{
    ifstream fin ("ctc.in");
    fin >> N >> M;
    for (i=1; i<=M; i++)
    {
        fin >> x >> y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
    fin.close();
    for (i=1; i<=N; i++)
        if (!seen[i])
            DFS(i);
    for (i=N; i>=1; i--)
        if (seen[postorder[i]])
        {
            no++;
            DFST(postorder[i]);
        }
    ofstream fout ("ctc.out");
    fout << no << '\n';
    for (i=1; i<=no; i++)
    {
        for (j=0; j<sol[i].size(); i++)
            fout << sol[i][j] << ' ';
        fout << '\n';
    }
    fout.close();
    return 0;
}

void DFS (unsigned int node)
{
    unsigned int i;
    seen[node] = 1;
    for (i=0; i<G[node].size(); i++)
        if (!seen[G[node][i]])
            DFS(G[node][i]);
    k++;
    postorder[k] = node;
}

void DFST (unsigned int node)
{
    unsigned int i;
    seen[node] = 0;
    sol[no].push_back(node);
    for (i=0; i<GT[node].size(); i++)
        if (seen[GT[node][i]])
            DFST(GT[node][i]);
}