Cod sursa(job #1768958)

Utilizator tudorgalatanRoman Tudor tudorgalatan Data 1 octombrie 2016 19:10:49
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>
#include <cstdlib>
#include <vector>

using namespace std;

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

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

unsigned int *A[100001], *AT[100001];
bool seen[100001];
unsigned int postorder[100001];
unsigned int i, j, k;

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

int main ()
{
    ifstream fin ("ctc.in");
    fin >> N >> M;
    for (i=1; i<=N; i++)
    {
        A[i] = (unsigned int *) realloc (A[i], sizeof (unsigned int));
        A[i][0] = 0;
        AT[i] = (unsigned int *) realloc (AT[i], sizeof (unsigned int));
        AT[i][0] = 0;
    }
    for (i=1; i<=M; i++)
    {
        fin >> x >> y;
        A[x][0]++;
        A[x] = (unsigned int *) realloc (A[x], (A[x][0]+1) * sizeof (unsigned int));
        A[x][A[x][0]] = y;
        AT[y][0]++;
        AT[y] = (unsigned int *) realloc (AT[y], (AT[y][0]+1) * sizeof (unsigned int));
        AT[y][AT[y][0]] = x;
    }
    fin.close();
    for (i=1; i<=N; i++)
        if (!seen[i])
            DFS(i);
    for (i=N; i>=1; i--)
        if (seen[postorder[i]])
        {
            solution++;
            DFST(postorder[i]);
        }
    ofstream fout ("ctc.out");
    fout << solution << '\n';
    for (i=1; i<=solution; i++)
    {
        for (j=0; j<sol[i].size(); j++)
            fout << sol[i][j] << ' ';
        fout << '\n';
    }
    fout.close();
    return 0;
}

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

void DFST (unsigned int node)
{
    unsigned int i;
    seen[node] = 0;
    sol[solution].push_back(node);
    for (i=1; i<=AT[node][0]; i++)
        if (seen[AT[node][i]])
            DFST(AT[node][i]);
}