题目链接:https://vjudge.net/problem/HDU-1269
学习博客:https://blog.youkuaiyun.com/qq_34374664/article/details/77488976
如果两个顶点可以相互通达,则称两个顶点强连通(strongly connected)。如果有向图G的每两个顶点都强连通,称G是一个强连通图。有向图的极大强连通子图,称为强连通分量(strongly connected components)
求给定的图是不是强连通图,非常基础的tarjan模板
dfn[ i ] : 在DFS中该节点被搜索的次序(时间戳)
low[ i ] : 为i或i的子树能够追溯到的最早的栈中节点的次序号
初学tarjan,记录一下模板
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 10005;
const int maxm = 100005;
int head[maxn];
int low[maxn], dfn[maxn];
int stk[maxn];
bool vis[maxn];
int cnt, ans, tot, index;
struct node
{
int to, next;
}e[maxm];
void init()
{
cnt = ans = tot = index = 0;
memset(vis, 0, sizeof(vis));
memset(dfn, 0, sizeof(dfn));
memset(low, 0, sizeof(low));
memset(head, -1, sizeof(head));
}
void addedge(int u, int v)
{
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt ++;
}
void tarjan(int x)
{
dfn[x] = low[x] = ++ tot;
stk[++ index] = x;
vis[x] = 1;
for(int i = head[x]; ~i; i = e[i].next)
{
if(! dfn[e[i].to])
{
tarjan(e[i].to);
low[x] = min(low[x], low[e[i].to]);
}
else if(vis[e[i].to])
{
low[x] = min(low[x], dfn[e[i].to]);
}
}
if(low[x] == dfn[x])
{
ans ++;
while(x != stk[index + 1])
{
vis[stk[index]] = 0;
index --;
}
}
}
int main()
{
int n, m;
while(scanf("%d%d", &n, &m) != EOF && (m + n))
{
init();
int u, v;
for(int i = 1; i <= m; i ++)
{
scanf("%d%d", &u, &v);
addedge(u, v);
}
for(int i = 1; i <= n; i ++)
{
if(! dfn[i]) tarjan(i);
}
if(ans == 1) printf("Yes\n");
else printf("No\n");
}
return 0;
}