HDU 1269 Labyrinth Castle

In order to train Xiaoxi's sense of direction, Gardon built a big castle with N rooms (N<=10000) and M passages (M<=100000), each passage is one-way, that is to say, if it is called A passage connects room A and room B, which only means that room A can reach room B through this passage, but it does not mean that room B can reach room A through it. Gardon needs to ask you to write a program to check whether any two rooms are connected to each other, 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 sets of data. The first line of the input has two numbers: N and M, and the next M lines have two numbers a and b in each line, indicating that a passage can go from room A to room B. The file ends with two zeros at the end.
 
Output
For each set of input data, if any two rooms are connected to each other, 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
Tarjan's Algorithm Naked Question
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <cassert>
#include <ctime>
#include <map>
#include <set>
using namespace std;
#pragma comment(linker, "/stck:1024000000,1024000000")
#define lowbit(x) (x&(-x))
#define max(x,y) (x>=y?x:y)
#define min(x,y) (x<=y?x:y)
#define MAX 100000000000000000
#define MOD 1000000007
#define pi acos(-1.0)
#define ei exp(1)
#define PI 3.1415926535897932384626433832
#define ios() ios::sync_with_stdio(true)
#define INF 0x3f3f3f3f
#define mem(a) ((a,0,sizeof(a)))
typedef long long ll;
int n,m,vis[10005],dnf[10005],low[10005],pos[10006];
int k,top,x,y;
vector<int>v[10005];
void tarjan(int u)
{
    low[u]=dnf[u]=++k;
    pos[++top]=u;
    vis[u]=1;
    for(int i=0;i<v[u].size();i++)
    {
        if(!dnf[v[u][i]])
        {
            tarjan (v [u] [i]);
            low[u]=min(low[u],low[v[u][i]]);
        }
        else if(vis[v[u][i]]) low[u]=min(low[u],dnf[v[u][i]]);
    }
}
intmain ()
{
    while(scanf("%d%d",&n,&m) && n+m)
    {
        memset(vis,0,sizeof(0));
        memset(dnf,0,sizeof(dnf));
        memset(low,0,sizeof(low));
        top=k=0;
        for(int i=0;i<=n;i++)
            v[i].clear();
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&x,&y);
            v[x].push_back(y);
        }
        tarjan(1);
        bool flag=true;
        for(int i=2;i<=n;i++)
            if(low[i]!=low[i-1]){flag=false;break;}
        puts(flag?"Yes":"No");
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325298298&siteId=291194637