版权声明:copy right https://blog.csdn.net/qq_43521140/article/details/90817601
Example:
①luogu P2661
②luogu P2921
Template_code:
#include<bits/stdc++.h>
#define fuck cout << "fuck" << endl;
#define mem(a,b) memset(a,b,sizeof(a))
#define Fast ios::sync_with_stdio(false);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int base = 13331;
const int MX = 1e5 + 7;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
vector<edge> G[MX];
int DFN[MX];
int LOW[MX];
bool ins[MX];
stack<int>s;
int timing;
int color[MX];//the number of SCC that node i belongs to
int colornum[MX];//the number of nodes that belongs to SCC i
int colorcnt;
//present node u
void tarjan(int u){
timing++;
DFN[u] = LOW[u] = timing;
s.push(u);
ins[u] = true;
for(int v : G[u]){
//if its son node hasn't been visted
if(DFN[v] == 0){
tarjan(v);
LOW[u] = min(LOW[u],LOW[v]);
}
//node v is not a key node
else if(ins[v] == true){
LOW[u] = min(LOW[u],DFN[v]);
}
}
//node u is a key node
if(DNF[u] == LOW[u]){
cnt++;
while(s.top() != u){
int tmp = s.top();
s.pop();
//out of the stack
ins[tmp] = false;
//node tmp belongs to SCC colorcnt
color[tmp] = colorcnt;
//the number of nodes SCC colorcnt has
colornum[colorcnt]++;
}
//the node u itself
s.pop();
color[u] = colorcnt;
colornum[colorcnt]++;
ins[u] = false;
}
}
int main(int argc, char const *argv[]){
#ifdef local
freopen("Input_File.txt","r",stdin);
freopen("Output_File.txt","w",stdout);
#endif
int n,m;
int x,y;
for(int i = 1;i <= m;++i){
cin >> x >> y;
G[x].push_back(y);
}
for(int i = 1;i <= n;++i){
if(DFN[i] == 0){
tarjan(i);
}
}
return 0;
}
/*
*/