Tarjan Algorithm

Zhiyuan Xu Lv1
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
namespace Tarjan{
const int MAXN = 1e5+5;
const int MAXM = 2e5+5;
int n,m,cnt,tot,in[MAXN],head[MAXN],dfn[MAXN],maxi[MAXN],low[MAXN],val[MAXN],curr,stt,scc[MAXN],num[MAXN],dp[MAXN],ans,a,b;
bool vis[MAXN];
vector<int> nums[MAXN];
stack<int> st;
struct Edge{
int f,t,nxt;
}edge[MAXM];
inline void add(int f,int t){
edge[++tot].f = f;
edge[tot].t = t;
edge[tot].nxt = head[f];
head[f] = tot;
}
inline void tarjan(int pos){
st.push(pos);
dfn[pos]=low[pos] = ++cnt;
vis[pos] = true;
for (int i=head[pos];i;i=edge[i].nxt){
int v = edge[i].t;
if (!dfn[v]){
tarjan(v);
low[pos] = min(low[pos],low[v]);
}else if (vis[v]) low[pos] = min(low[pos],dfn[v]);
}
if (low[pos]==dfn[pos]){
curr++;
do{
stt = st.top();
st.pop();
vis[stt] = false;
scc[stt] = curr;
nums[curr].push_back(stt);
val[curr]+=num[stt];
}while(stt!=pos);
}
}
inline void tarj(){
for (int i=1;i<=n;i++) if (!dfn[i]) tarjan(i);
}
inline void dfs(int pos){
vis[pos] = true;
dp[pos] = val[pos];
int addi = 0;
for (int i : nums[pos]){
for (int j=head[i];j;j=edge[j].nxt){
int v = scc[edge[j].t];
if(v==pos) continue;
if (!vis[v]) dfs(v);
addi = max(addi,dp[v]);
}
}

dp[pos]+=addi;
ans = max(ans,dp[pos]);
}
inline void topo(){
queue<int> q;
unordered_map<int,unordered_map<int,bool> > mp,mp2;
for (int i=1;i<=curr;i++){
for (int j : nums[i]){
for (int k=head[j];k;k=edge[k].nxt){
int v = scc[edge[k].t];
if (v==i || mp[i][v]) continue;
mp[i][v] = true;
in[v]++;
}
}
}
swap(mp,mp2);
for(int i=1;i<=curr;i++) {
ans = max(ans,val[i]);
if (!in[i]) q.push(i);
}
while(!q.empty()){
int qf = q.front(); q.pop();
dp[qf]+=val[qf]+maxi[qf];
ans = max(ans,dp[qf]);
for (int i : nums[qf]){
for (int j=head[i];j;j=edge[j].nxt){
int v = scc[edge[j].t];
if (v==qf) continue;
if (!mp[qf][v] && in[v]){
mp[qf][v] = true;
maxi[v] = max(maxi[v],dp[qf]);
if ((--in[v])==0) q.push(v);
}
}
}
}
}
inline void init();
inline void solve();
}
  • Title: Tarjan Algorithm
  • Author: Zhiyuan Xu
  • Created at : 2024-07-05 23:58:06
  • Updated at : 2024-07-05 23:58:31
  • Link: https://redefine.ohevan.com/Template/Tarjan/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Tarjan Algorithm