HDU 1269(tarjin)

这篇博客主要介绍了如何利用Tarjan算法解决一个图论问题——判断在一个有向图中,所有房间是否两两相互连通。题目来源于HDU 1269,要求编写程序检查是否存在从任意房间i到房间j以及从房间j到房间i的路径。博主给出了解题思路,即判断所有节点是否构成一个环,并提供了代码实现。
摘要由CSDN通过智能技术生成

Problem Description
为了训练小希的方向感,Gardon建立了一座大城堡,里面有N个房间(N<=10000)和M条通道(M<=100000),每个通道都是单向的,就是说若称某通道连通了A房间和B房间,只说明可以通过这个通道由A房间到达B房间,但并不说明通过它可以由B房间到达A房间。Gardon需要请你写个程序确认一下是否任意两个房间都是相互连通的,即:对于任意的i和j,至少存在一条路径可以从房间i到房间j,也存在一条路径可以从房间j到房间i。

Input
输入包含多组数据,输入的第一行有两个数:N和M,接下来的M行每行有两个数a和b,表示了一条通道可以从A房间来到B房间。文件最后以两个0结束。

Output
对于输入的每组数据,如果任意两个房间都是相互连接的,输出"Yes",否则输出"No"。

Sample Input

3 3
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0

Sample Output

Yes
No

解题思路:就是判断所有点是不是一个环,套tarjin 的板子,然后看最后col是不是等于1就可以啦。

代码:

#pragma GCC optimize(2)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <bitset>
#include <queue>
//#include <random>
#include <time.h>
using namespace std;
#define int long long
#define ull unsigned long long
#define ls root<<1
#define rs root<<1|1
const int maxm = 100000+100;
const int maxn=10000+100;
//std::mt19937 rnd(time(NULL));
struct edge
{
    int v,next;
}e[maxm];
int head[maxn],cnt,dfn[maxn],low[maxn],tot,st[maxn],top,vis[maxn],col;
inline void add(int a,int b)
{
    e[++cnt]=edge{b,head[a]};
    head[a]=cnt;
}
void tarjin(int u)
{
    dfn[u]=low[u]=++tot;
    st[++top]=u;
    for(int i=head[u];i;i=e[i].next){
        int v=e[i].v;
        if(!dfn[v]){
            tarjin(v);
            low[u]=min(low[u],low[v]);
        }
        else if(!vis[v]) low[u]=min(low[u],dfn[v]);
    }
    if(low[u]==dfn[u]){
        ++col,vis[u]=1;
        while(st[top]!=u){
            int x=st[top];
            vis[x]=1;
            top--;
        }
        top--;
    }
}
signed main()
{
    int n,m;
    while(~scanf("%lld%lld",&n,&m) && (n||m)){
        cnt=tot=col=top=0;
        memset(head,0,sizeof head);
        memset(dfn,0,sizeof dfn);
        memset(low,0,sizeof low);
        memset(vis,0,sizeof vis);
        for(int i=1;i<=m;i++){
            int a,b;
            scanf("%lld%lld",&a,&b);
            add(a,b);
        }
        for(int i=1;i<=n;i++){
            if(!dfn[i]) tarjin(i);
        }
        if(col==1){
            puts("Yes");
        }
        else puts("No");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值