-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathscc.cpp
More file actions
106 lines (101 loc) · 1.97 KB
/
scc.cpp
File metadata and controls
106 lines (101 loc) · 1.97 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <class T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define int long long int
#define pb push_back
#define pi pair<int, int>
#define pii pair<int, pi>
#define fir first
#define sec second
#define MAXN 500005
#define mod 1000000007
int n, m;
bool vis[MAXN];
int root[MAXN];
vector<int> order;
vector<int> roots;
vector<int> comp;
vector<vector<int>> comps;
vector<int> adj[MAXN];
vector<int> adj_rev[MAXN];
vector<int> adj_scc[MAXN];
void dfs(int v)
{
vis[v] = true;
for (auto const &u : adj[v])
if (!vis[u])
dfs(u);
order.pb(v);
}
void dfs2(int v)
{
comp.pb(v);
vis[v] = true;
for (auto const &u : adj_rev[v])
if (!vis[u])
dfs2(u);
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
adj[a].pb(b);
adj_rev[b].pb(a);
}
for (int i = 0; i < n; i++)
{
if (!vis[i])
dfs(i);
}
reverse(order.begin(), order.end());
memset(vis, false, sizeof(vis));
for (auto const &v : order)
{
if (!vis[v])
{
comp.clear();
dfs2(v);
comps.pb(comp);
// making condensation graph
/*
int r = comp.back();
for (auto const &u : comp)
root[u] = r;
roots.push_back(r);
*/
}
}
// making condensation graph
/*
for (int v = 0; v < n; v++)
{
for (auto const &u : adj[v])
{
int root_v = roots[v];
int root_u = roots[u];
if (root_u != root_v)
adj_scc[root_v].pb(root_u);
}
}
*/
// printing scc
cout << comps.size() << endl;
for (auto const &comp : comps)
{
cout << comp.size() << " ";
for (auto const &u : comp)
cout << u << " ";
cout << endl;
}
return 0;
}
// to test: https://judge.yosupo.jp/problem/scc