思路:这题运用到tarjan算法 刚看这个算法一脸蒙b,然后通过阅读别人的博客算是掌握的差不多了。这个算法中用到两个数组第一个dfn[],low[],第一个数组是用来记录深搜的顺序的,第二个数组是用来保存i节点能够追溯到他这个强连通分量最先深搜到的那个节点。具体的看算法有关键注释。我这里简单说下这个算法推荐大家看下这个博客,他这里讲的非常的详细,http://blog.csdn.net/mengxiang000000/article/details/51672725,这个网址。
迷宫城堡
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
代码:
#include<stdio.h>//我这里采用邻居表存储图的。第一次用的邻接矩阵发现超内存了。
#include<string.h>
#include<stdlib.h>
#define MAX 100001
typedef int VexType;
struct Vnode{
VexType data;
struct Vnode *next;
};
typedef Vnode Lgraph[MAX];
/* Vnode是顶点的结点结构 */
Lgraph map;
int n,m;
int dfn[10001],low[100001],sign,count;
bool flag[10001];
void creat_L(Lgraph G){// 最后输入的边在前面头插法,建立。
Vnode *p,*q;
int i,j,k;
for(i=1; i<=n; i++) {
G[i].data=i; G[i].next=NULL;
}
for(k=1;k<=m; k++){
scanf("%d%d",&i,&j);
/* p结点链接到第j条链 */
/* q=(Vnode *)malloc(sizeof(Vnode));
q->data=i;
q->next=G[j].next;G[j].next=q;*/
q=(Vnode *)malloc(sizeof(Vnode));
q->data=j;
q->next=G[i].next; G[i].next=q; /* q结点链接到第i条链 */
}
}
void out_L(Lgraph G){
int i;
Vnode *p;
for (i=1; i<=n; i++) {
p=G[i].next;
while(p!=NULL){
printf("%5d",p->data); p=p->next;
}
printf("\n");
}
}
int min(int x,int y)
{
if(x<y) return x;
return y;
}
int tarjan(int u)
{ int v;
flag[u]=1;
dfn[u]=low[u]=count++;//一开始将第一个深搜的节点来了。将这个节点的顺序为count
Vnode *p=map[u].next;
while(p)
{
v=p->data;//循环所有与他相连的点
if(flag[v]==0) { tarjan(v); low[v]= min(low[u],low[v]);}//如果有点并且这个点没有被访问就深搜,回来的时候将low的值改变,因为强连通//分量肯定是有环的。
if(flag[v]==1) low[u]=min(low[u],low[v]);//当这个节点被访问了那就是这个强连通分量撞到环了。然后将low值赋值为小的。
p=p->next;
}
/* for(int v=1;v<=m;v++)
{
if(map[u][v]!=0)//
{ if(!flag[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(flag[v]==1)low[u]=min(low[u],low[v]);
}
}*/
if(dfn[u]==low[u])//回溯回去当他两相等也就是这个没有遇到环或者是 这个节点是强连通分量的第一个深搜的节点就将sign计数器加1
{
sign++;
}
}
int main()
{
while(scanf("%d%d",&n,&m)&&n)
{creat_L(map);
sign=0;
count=1;
//out_L(map);
memset(low,0,sizeof(low));
memset(flag,0,sizeof(flag));
memset(dfn,0,sizeof(dfn));
for(int i=1;i<=n;i++)
{tarjan(i);
}
if(sign>1) printf("No\n");
else printf("Yes\n");
}
}