Pagini recente » Cod sursa (job #1890568) | Cod sursa (job #523909) | Cod sursa (job #1300864) | Cod sursa (job #2731838) | Cod sursa (job #1941740)
#include<cstdio>
#define N_MAX 100000
using namespace std;
struct nod
{
int val;
nod *next;
};
nod *List[N_MAX+1], *L[N_MAX+1], *ctc[N_MAX+1];
bool viz[N_MAX+1];
int st[N_MAX], vf, n, m, nrc;
inline void Insert(int x, int y)
{
nod *elem = new nod;
elem->val = y;
elem->next = List[x];
List[x] = elem;
}
inline void InsertReverseGraph(int x, int y)
{
nod *elem = new nod;
elem->val = y;
elem->next = L[x];
L[x] = elem;
}
void Read()
{
int i, x, y;
FILE *fin = fopen("ctc.in","r");
fscanf(fin,"%d%d",&n,&m);
for(i=1; i<=m; i++)
{
fscanf(fin,"%d%d",&x,&y);
Insert(x,y);
InsertReverseGraph(y,x);
}
fclose(fin);
}
void DFS(int x)
{
viz[x] = true;
nod *p = List[x];
while(p != NULL)
{
if(!viz[p->val])
DFS(p->val);
p = p->next;
}
st[vf++] = x;
}
void DFSReverseGraph(int x)
{
viz[x] = true;
nod *elem = new nod;
elem->val = x;
elem->next = ctc[nrc];
ctc[nrc] = elem;
nod *p = L[x];
while(p != NULL)
{
if(!viz[p->val])
DFSReverseGraph(p->val);
p = p->next;
}
}
int main()
{
int i;
nod *l;
FILE *fout = fopen("ctc.out","w");
Read();
for(i=1; i<=n; i++)
if(!viz[i])
DFS(i);
for(i=1; i<=n; i++)
viz[i] = false;
while(vf > 0)
{
vf--;
if(!viz[st[vf]])
{
nrc++;
DFSReverseGraph(st[vf]);
}
}
fprintf(fout,"%d\n",nrc);
for(i=1; i<=nrc; i++)
{
l = ctc[i];
while(l != NULL)
{
fprintf(fout,"%d ",l->val);
l = l->next;
}
fprintf(fout,"\n");
}
fclose(fout);
return 0;
}