/*强连通分量 模板题 tarjan算法写的
*/
#include<cstdio>
#include<cstring>#include<stack>
#include<vector>
using namespace std;
int scc[100100],m,n;
int dfn[100100],low[100100],times,ma,mb,scc_cnt;
stack<int> q;
vector<int> map[100100];
int dfs(int u)
{
dfn[u] = low[u] = ++times;
q.push(u);
for(int i = 0; i < map[u].size(); i++)
{
int v = map[u][i];
if(!dfn[v])
{
dfs(v);
low[u] = min(low[u],low[v]);
}
else if(!scc[v])
{
low[u] = min(low[u],dfn[v]);
}
}
if(low[u]==dfn[u])
{
scc_cnt++;
while(1)
{
int x = q.top();
q.pop();
scc[x] = scc_cnt;
if(x==u) break;
}
}
}
int main()
{
while(scanf("%d %d",&n,&m)==2)
{
if(!m&&!n) break;
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(scc,0,sizeof(scc));
for(int i = 0; i <= n; i++)
map[i].clear();
int a,b;
for(int i = 0; i < m; i++)
{
scanf("%d%d",&a,&b);
map[a].push_back(b);
}
scc_cnt = times = 0;
for(int i = 1; i <= n; i++)
if(!dfn[i])
dfs(i);
if(scc_cnt==1)
printf("Yes\n");
else printf("No\n");
}
return 0;
}
本文介绍使用Tarjan算法求解图中的强连通分量(SCC)问题。通过深度优先搜索(DFS)的方式,该算法能有效地找出图中所有节点的所属强连通分量,为图论问题提供解决方案。
196

被折叠的 条评论
为什么被折叠?



