hdu 1269 Tarjan judge strongly connected graph

Problem Description
In order to train Xiaoxi's sense of direction, gardon built A large castle with N rooms (N < = 10000) and M channels (m < = 100000). Each channel is unidirectional, that is to say, if A channel connects room A and room B, it only means that it can reach room B from room A through this channel, but it does not mean that it can reach room A from room B. Gardon needs to ask you to write A program to confirm whether any two rooms are interconnected, that is, for any i and j, there is at least one path from room i to room J, and there is also A path from room J to room i.

Input
The input contains multiple groups of data. The first row of input has two numbers: N and M. the next row of M has two numbers a and B, indicating that a channel can come from room a to room B. The file ends with two zeros.

Output
For each group of input data, if any two rooms are interconnected, output "Yes", otherwise output "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

Explanation:

Determine whether the graph is strongly connected or not.
The strong connected component of Tarjan is 1

Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;

const int maxn = 10010;

vector<int> G[maxn];
int pre[maxn],lowlink[maxn],sccno[maxn],dfs_clock,scc_cnt;
stack<int> S;

void dfs(int u)
{
    pre[u] = lowlink[u] = ++dfs_clock;
    S.push(u);
    for(int i=0;i<G[u].size();i++)
    {
        int v = G[u][i];
        if(!pre[v])
        {
            dfs(v);
            lowlink[u] = min(lowlink[u],lowlink[v]);
        }else if(!sccno[v])
        {
            lowlink[u] = min(lowlink[u],pre[v]);
        }
    }
    if(lowlink[u] == pre[u])
    {
        scc_cnt++;
        for(;;)
        {
            int x = S.top();S.pop();
            sccno[x] = scc_cnt;
            if(x == u) break;
        }
    }
}

void find_scc(int n)
{
    dfs_clock = scc_cnt = 0;
    memset(sccno,0,sizeof(sccno));
    memset(pre,0,sizeof(pre));
    for(int i=1;i<=n;i++)
        if(!pre[i]) dfs(i);
}

int main()
{
    int n,m;
    while(cin>>n>>m,n+m)
    {
        for(int i=1;i<=n;i++) G[i].clear();
        int a,b;
        for(int i=0;i<m;i++)
        {
             scanf("%d%d",&a,&b);
             G[a].push_back(b);
        }
        find_scc(n);
        if(scc_cnt==1) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
    return 0;
}

Posted by MrPotatoes on Tue, 31 Mar 2020 10:36:27 -0700