Pagini recente » Cod sursa (job #2200079) | Cod sursa (job #2277367) | Cod sursa (job #2951683) | Cod sursa (job #292228) | Cod sursa (job #3224744)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 100000
#define M 200000
typedef struct
{
int vf, urm;
} element;
element succ[M+1], pred[M+1], ctc[N+1];
int lst_s[N+1], lst_p[N+1], lst_ctc[N+1], nr_s, nr_p, nr_ctc;
int sort_top[N+1], n_s_t;
bool viz[N+1];
void adauga_s(int x, int y)
{
++nr_s;
succ[nr_s].vf = y;
succ[nr_s].urm = lst_s[x];
lst_s[x] = nr_s;
}
void adauga_p(int x, int y)
{
++nr_p;
pred[nr_p].vf = y;
pred[nr_p].urm = lst_p[x];
lst_p[x] = nr_p;
}
void dfs(int x)
{
viz[x] = true;
for (int p = lst_s[x]; p != 0; p = succ[p].urm)
{
int y = succ[p].vf;
if (!viz[y])
{
dfs(y);
}
}
sort_top[++n_s_t] = x;
}
void dfs_t(int x, int n_ctc)
{
viz[x] = true;
nr_ctc++;
ctc[nr_ctc].vf = x;
ctc[nr_ctc].urm = lst_ctc[n_ctc];
lst_ctc[n_ctc] = nr_ctc;
for (int p = lst_p[x]; p != 0; p = pred[p].urm)
{
int y = pred[p].vf;
if (!viz[y])
{
dfs_t(y, n_ctc);
}
}
}
int main()
{
FILE *in, *out;
in = fopen("ctc.in", "r");
out = fopen("ctc.out", "w");
int n, m;
fscanf(in, "%d%d", &n, &m);
for (int i = 0; i < m; i++)
{
int x, y;
fscanf(in, "%d%d", &x, &y);
adauga_s(x, y);
adauga_p(y, x);
}
for (int i = 1; i <= n; i++)
{
if (!viz[i])
{
dfs(i);
}
}
for (int i = 1; i <= n; i++)
{
viz[i] = false;
}
int n_ctc = 0;
for (int i = n_s_t; i >= 1; i--)
{
int x = sort_top[i];
if (!viz[x])
{
++n_ctc;
dfs_t(x, n_ctc);
}
}
fprintf(out, "%d\n", n_ctc);
for (int i = 1; i <= n_ctc; i++)
{
///afisam varfurile din ctc cu numarul i
for (int p = lst_ctc[i]; p != 0; p = ctc[p].urm)
{
fprintf(out, "%d ", ctc[p].vf);
}
fprintf(out, "\n");
}
fclose(in);
fclose(out);
return 0;
}