-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtarjan.cpp
67 lines (66 loc) · 958 Bytes
/
tarjan.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<stack>
#include<cstdio>
using namespace std;
int point[4000],had[4000],nxt[4000];
int tot,sum;
int dns[4000],low[4000];
bool vis[4000];
stack<int>s;
void add(int a,int b)
{
tot++;
point[tot]=b;
nxt[tot]=had[a];
had[a]=tot;
}
void tarjine(int x)
{
s.push(x);
vis[x]=1;
dns[x]=low[x]=++sum;
for(int i=had[x];i;i=nxt[i])
{
int to=point[i];
if(!dns[to])
{
tarjine(to);
low[x]=min(low[x],low[to]);
}
else
{
if(vis[to])low[x]=min(low[x],dns[to]);
}
}
if(dns[x]==low[x])
{
while(!s.empty())
{
int y=s.top();
cout<<y<<' ';
vis[y]=0;
s.pop();
if(y==x)break;
}
cout<<endl;
}
}
int main()
{
// freopen("in.txt","r",stdin);
int n;
int m;
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
add(a,b);
}
for(int i=1;i<=n;i++)
{
sum=0;
if(!dns[i])tarjine(i);
}
return 0;
}