zoukankan      html  css  js  c++  java
  • 迷宫城堡 强连通分量(scc-tarjan)

    迷宫城堡

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 12923    Accepted Submission(s): 5777


    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
     
    Author
    Gardon
     
    Source
     
    Recommend
    lxj   |   We have carefully selected several similar problems for you:  1233 1142 1217 1162 1102
     
     
    #include <cstdio>
    #include <vector>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    
    int n;
    const int maxn=10010;
    vector<int> g[maxn];
    
    int cnt,top,index;// 强连通分量个数  栈顶 时间戳
    int low[maxn],dfn[maxn];//DFN(u)为节点u搜索的次序编号(时间戳),Low(u)为u或u的子树能够追溯到的最早的栈中节点的次序号
    int belong[maxn],stack[maxn];//  belong 表示强连通 
    bool instack[maxn];// 是否包含在栈内
    
    void init(){
        cnt=top=index=0;
        for(int i=1;i<=n;i++)   low[i]=dfn[i]=0;
    }
    
    void tarjan(int u){
        stack[top++]=u;
        instack[u]=1;
        low[u]=dfn[u]=++index;
        for(int i=0;i<g[u].size();i++){
            int v=g[u][i];
            if(!dfn[v]){
                tarjan(v);
                low[u]=min(low[v],low[u]);
            }
            else{
                if(instack[v])
                    low[u]=min(low[u],dfn[v]);
            }
        }
        if(low[u]==dfn[u]){
                cnt++;
                int v;
                do{
                    v= stack[--top];
                    instack[v]=0;
                    belong[v]=cnt;
                }while(u!=v);
        }
    }
    
    int main(){
        int m;
        //freopen("data.in","r",stdin);
        while(scanf("%d%d",&n,&m),m+n){
            for(int i=1;i<=n;i++)   g[i].clear();
            while(m--){
                int x,y;
                scanf("%d%d",&x,&y);
                g[x].push_back(y);
            }
            init();
            for(int i=1;i<=n;i++)
                if(!dfn[i])
                    tarjan(1);
            printf(cnt==1?"Yes
    ":"No
    ");
        }
    }

    参考  https://www.byvoid.com/zhs/blog/scc-tarjan

  • 相关阅读:
    627. Swap Salary
    176. Second Highest Salary
    596. Classes More Than 5 Students
    183. Customers Who Never Order
    181. Employees Earning More Than Their Managers
    182. Duplicate Emails
    175. Combine Two Tables
    620. Not Boring Movies
    595. Big Countries
    HDU 6034 Balala Power! (贪心+坑题)
  • 原文地址:https://www.cnblogs.com/acmtime/p/5788922.html
Copyright © 2011-2022 走看看