HDU 1269 迷宫城堡(强连通图的判定)

本文介绍了一种使用Tarjan算法解决迷宫城堡问题的方法,该问题要求判断在一座由多个房间和通道组成的城堡中,任意两个房间是否都能通过一系列通道相互连通。文章详细解释了如何构建有向图,应用Tarjan算法求解强连通分量,并最终确定城堡的连通性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

迷宫城堡
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8196    Accepted Submission(s): 3664


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
 

模板题

// Tarjan算法求有向图强连通分量并缩点
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int N = 100010, M = 1000010;
int ver[M], Next[M], head[N], dfn[N], low[N];
int ss[N], ins[N], c[N];
int vc[M], nc[M], hc[N], tc;
vector<int> scc[N];
int n, m, tot, num, top, cnt;
void init()
{
	tot=0;
	num=0;
	top=0;
	cnt=0;
	memset(dfn,0,sizeof(dfn));
	memset(low,0,sizeof(low));
	memset(ver,0,sizeof(ver));
	memset(head,0,sizeof(head));
}
void add(int x, int y) {
	ver[++tot] = y, Next[tot] = head[x], head[x] = tot;
}

void add_c(int x, int y) {
	vc[++tc] = y, nc[tc] = hc[x], hc[x] = tc;
}

void tarjan(int x) {
	dfn[x] = low[x] = ++num;
	ss[++top] = x, ins[x] = 1;
	for (int i = head[x]; i; i = Next[i])
		if (!dfn[ver[i]]) {
			tarjan(ver[i]);
			low[x] = min(low[x], low[ver[i]]);
		}
		else if (ins[ver[i]])
			low[x] = min(low[x], dfn[ver[i]]);
	if (dfn[x] == low[x]) 
	{
		cnt++; 
	    int y;
		do {
			y = ss[top--], ins[y] = 0;
			c[y] = cnt, scc[cnt].push_back(y);
		} while (x != y);
	}
}

int main() 
{
	while(scanf("%d%d",&n,&m)!=-1)
	{
	
		if(n==0&&m==0)break;
		init();
		for(int i = 1; i <= m; i++)
		{
		   int x, y;
		  scanf("%d%d", &x, &y);
		  add(x,y);
		}
	   for(int i = 1; i <= n; i++)
		if (!dfn[i]) tarjan(i);
		//cout<<cnt<<endl;
		if(cnt==1)
			printf("Yes\n") ;
		else
			printf("No\n") ;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值