参见大佬的博客
大佬无敌,菜菜的我又get了个新技能
tarjan算法就是利用了栈维护了深度优先搜索的时间标记,找到存在的强联通分量,然后缩点为DAG。感觉大佬讲得很详细了,看完了我尝试着手撕代码,结果手指撕断了都没成,正式菜哭了。今天看了邝大神的模板总算磕磕绊绊的撕完了。
code:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<string>
#include <set>
using namespace std;
const double eps=1e-8;
const int MAXN = 20010;//点数
const int MAXM = 50010;//边数
const int inf=0x3f3f3f3f;
int read() { //输入外挂
int res = 0;
bool flag =false;
char ch;
if((ch = getchar()) == '-') flag = true;
else if(ch >= '0' && ch <= '9') res = ch - '0';
while((ch = getchar()) >= '0' && ch <= '9')
res = res * 10 + (ch - '0');
return flag ? -res : res;
}
struct Edge
{
int to,next;
}edge[MAXM];
int head[MAXN],tot;//链式前向星所用变量
int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN];//Belong数组的值是1~scc,Belong[i]代表第i个点属于哪个强联通分量
int Index,top;
int scc;//强连通分量的个数
bool Instack[MAXN];
//Stack数组和Instack数组模拟栈的操作
int num[MAXN];//各个强连通分量包含点的个数,数组编号1~scc
//num数组不一定需要,结合实际情况
void addedge(int u,int v)//添加边
{
edge[tot].to = v;edge[tot].next = head[u];head[u] = tot++;
}
void Tarjan(int u)
{
int v;
Low[u] = DFN[u] = ++Index;
Stack[top++] = u;
Instack[u] = true;
for(int i = head[u];i != -1;i = edge[i].next)//遍历以u为起点的边,如边的另一个节点已经在栈内就更新Low
{
v = edge[i].to;
if( !DFN[v] )
{
Tarjan(v);
if( Low[u] > Low[v] )Low[u] = Low[v];
}
else if(Instack[v] && Low[u] > DFN[v])
Low[u] = DFN[v];
}
if(Low[u] == DFN[u])//如果找到了一个强联通分量,记录并缩点
{
scc++;
do
{
v = Stack[--top];
Instack[v] = false;
Belong[v] = scc;
num[scc]++;
}while( v != u);
}
}
void solve(int N)
{
int ans=0;
for(int i = 1;i <= N;i++)//遍历所有节点
if(!DFN[i])
Tarjan(i);
}
void init()//初始化函数
{
tot = 0;
Index = scc = top = 0;
memset(DFN,0,sizeof(DFN));
memset(Instack,false,sizeof(Instack));
memset(num,0,sizeof(num));
memset(head,-1,sizeof(head));
memset(Low,0,sizeof(Low));
memset(Belong,0,sizeof(Belong));
memset(Stack,0,sizeof(Stack));
}
void in(int m)
{
int u,v;
for(int i=0;i<m;i++)
{
u=read();
v=read();
addedge(u,v);
}
}
int main()
{
int res;
int n,m;
while(scanf("%d%d", &n,&m)!=EOF)
{
init();
in(m);
solve(n);
}
return 0;
}