Castle labyrinth (Strongly communication)

Castle labyrinth (Strongly communication)

topic

In order to train small Greek sense of direction, Gardon built a large castle, inside the room there are N (N <= 10000) and M channels (M <= 100000), each channel is unidirectional, that if called a passage communicating the room a and room B, a room B can be reached only by the described rooms a through this channel, but does not indicate the room can reach a B room through it. Gardon need to ask you to write a program to confirm whether any two rooms are interconnected, namely: for any i and j, there is at least one path from room to room j i, j may also exist a path from room to the room i.
Input
input comprising a plurality of sets of data, the first line of input has two numbers: N and M, the next M lines each with two numbers, a and B, may represent a channel from A to B room room. File and end with two zeroes.
Output
For each set of input data, if any two rooms are interconnected, the output of "Yes", and otherwise outputs "No".
The Input the Sample
. 3. 3
. 1 2
2. 3
. 3. 1
. 3. 3
. 1 2
2. 3
. 3 2
0 0
the Sample the Output
Yes
No

The meaning of problems

And only determines whether a strongly connected components

answer

#include <cstdio>
#include <algorithm>
#include <string.h>
#include <vector>
#include <iostream>
#include <stack>
#define N 75005
using namespace std;
vector<int> eg[N];
stack<int> sk;
int idx = 0;
int dfn[N], low[N], ins[N], cnt = 0;
void tarjan(int u)
{
    dfn[u] = low[u] = ++idx;
    sk.push(u);
    ins[u] = 1;
    for (int v : eg[u])
    {
        if (!dfn[v])
        {
            tarjan(v);
            low[u] = min(low[u], low[v]);
        }
        else if (ins[v])
        {
            low[u] = min(low[u], dfn[v]);
        }
    }
    int tem;
    if (dfn[u] == low[u])
    {
        cnt++;
        do
        {
            tem = sk.top();
            sk.pop();
            ins[tem] = 0;
        } while (tem != u);
    }
}

int main()
{
    int n, m, x, y;
    while (scanf("%d%d", &n, &m) && n)
    {
        memset(ins, 0, sizeof(ins));
        memset(low, 0, sizeof(low));
        memset(dfn, 0, sizeof(dfn));
        for (int i = 0; i < m; i++)
        {
            cin >> x >> y;
            eg[x].push_back(y);
        }
        idx = 0;
        cnt = 0;
        for(int i=1;i<= n;i++)
        if(!dfn[i])
        tarjan(i);

        if (cnt == 1)
        {

            cout << "Yes" << endl;
        }
        else
        {
            cout << "No" << endl;
        }
        for (int i = 1; i <= n; i++)
        {
            eg[i].clear();
        }
    }
}

Guess you like

Origin www.cnblogs.com/tttfu/p/11274040.html