HDU 1269 迷宫城堡(强联通模板题)

来源:互联网 发布:淘宝泊泉雅都是假的吗 编辑:程序博客网 时间:2024/05/18 01:15

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1269


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 31 22 33 13 31 22 33 20 0
 

Sample Output
YesNo
 

Author
Gardon
 

Source
HDU 2006-4 Programming Contest


代码如下:

#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;/** Tarjan算法* 复杂度O(N+M)*/const int MAXN = 20010;//点数const int MAXM = 100010;//边数struct Edge{    int to,next;} edge[MAXM];int head[MAXN],tot;int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN];//Belong数组的值是1~sccint Index,top;int scc;//强连通分量的个数bool Instack[MAXN];int num[MAXN];//各个强连通分量包含点的个数,数组编号1~scc//num数组不一定需要,结合实际情况void addEdge(int u,int v){    edge[tot].to = v;    edge[tot].next = head[u];    head[u] = tot++;}void Tarjan(int u){    int v;    Low[u] = DFN[u] = ++Index;    Stack[top++] = u;    Instack[u] = true;    for(int i = head[u]; i != -1; i = edge[i].next)    {        v = edge[i].to;        if( !DFN[v] )        {            Tarjan(v);            if( Low[u] > Low[v] )Low[u] = Low[v];        }        else if(Instack[v] && Low[u] > DFN[v])            Low[u] = DFN[v];    }    if(Low[u] == DFN[u])    {        scc++;        do        {            v = Stack[--top];            Instack[v] = false;            Belong[v] = scc;            num[scc]++;        }        while( v != u);    }}void solve(int N){    memset(DFN,0,sizeof(DFN));    memset(Instack,false,sizeof(Instack));    memset(num,0,sizeof(num));    Index = scc = top = 0;    for(int i = 1; i <= N; i++)        if(!DFN[i])            Tarjan(i);}void init(){    tot = 0;    memset(head,-1,sizeof(head));}int main(){    int n, m;    while(~scanf("%d%d",&n,&m))    {        init();        if(n==0 && m==0)            break;        for(int i = 1; i <= m; i++)        {            int x, y;            scanf("%d%d",&x,&y);            addEdge(x, y);        }        solve(n);        if(scc > 1)        {            printf("No\n");        }        else            printf("Yes\n");    }    return 0;}


0 0
原创粉丝点击