hdu1269 tarjan模板题

http://acm.hdu.edu.cn/showproblem.php?pid=1269

题意:判断是否存在从任意一个起点开始都可以走完余下任何一个点。

解题思路:有向联通图,判断联通分量是否为1即可

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<bitset>
using namespace std;
#define N 100005
stack<int>S;
vector<int>V[N];
bool instack[N];//instack[i]为真表示i在栈中
int DFN[N],LOW[N];
int Belong[N];//Belong[i] = a; 表示i这个点属于第a个连通分量
int Bcnt,Dindex;//Bcnt用来记录连通分量的个数,Dindex表示到达某个点的时间
void tarjan(int u)
{
    int v;
    DFN[u]=LOW[u] = ++Dindex;//这里要注意 Dindex是初始化为0,这里就不能 Dindex++; 不然第一个点的DFN和LOW就为0
    S.push(u);
    instack[u] = true;
    for (int i=0;i<V[u].size();i++)//对所有可达边的搜索
    {
        v = V[u][i];
        if (!DFN[v])//if (v is not visited)
        {
            tarjan(v);
            LOW[u]=min(LOW[u],LOW[v]);
        }
        else if (instack[v])
        {
            LOW[u]=min(LOW[u],DFN[v]);// 注意是DFN
        }
    }
    if (DFN[u] == LOW[u])//这里表示找完一个强连通啦
    {
        Bcnt ++;//强连通个数加1
        do
        {
            v = S.top();
            S.pop();
            instack[v] = false;
            Belong[v] = Bcnt;
        }
        while (u != v);//一直到v=u都是属于第Bcnt个强连通分量
    }
}
void callTarjan(int n)
{
    for (int i=1;i<=n;i++)//这里是一定要对所有点tarjan才能求出所有的点的强连通分量
        if (!DFN[i])
            tarjan(i);
}
void init(int n)
{
	for(int i=1;i<=n;i++)
	{V[i].clear();}
	Bcnt = Dindex = 0;
    memset(DFN,0,sizeof(DFN));
	while(!S.empty())
	{S.pop();}
}
int main()
{
    int i,j,k;
    int n,m,t;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
		if(n==0&&m==0) break;
		init(n);
		while(m--)
		{
			int from,to;
			scanf("%d%d",&from,&to);
			V[from].push_back(to);
		}
		callTarjan(n);//调用
		if(Bcnt==1)//强连通分量只有一个,说明全部点构成的图是强连通图
		{printf("Yes\n");}
		else
		{printf("No\n");}
    }
}
/*
input:
3 3
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0
output:
Yes
No
*/
参考资料:

https://www.byvoid.com/blog/scc-tarjan

http://blog.csdn.net/zyy173533832/article/details/12583589

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值