Strong graph tarjan-hdu1269 labyrinth Castle

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". 
Sample Input

3 3
1 2
2 3
3 1
3 3
1 2
2 3
3 2
0 0

Sample Output

Yes 
No 

with a similar idea dfs, for each point maintains two values, dfn is to be searched when the time stamp, low that it contains the root of a minimal tree. When low == dfn, connected to it around the circle, it should be added to the strongly connected graph.
stack<int>sta;
vector<int>gra[N];
int dfn[N],low[N],now,vis[N],sum;
int n,m;
 
void ini(void)
{
    memset(dfn,0,sizeof(dfn));
    memset(low,0,sizeof(low));
    memset(vis,0,sizeof(vis));
    now=sum=0;
    for(int i=1;i<=n;i++)
        gra[i].clear();
    while(sta.empty()==0)
        sta.pop();
}
 
void tarjan(int s,int p)
{
    vis[s]=2;
    dfn[s]=low[s]=++now;
    sta.push(s);
    for(int i=0;i<gra[s].size();i++)
    {
        int t=gra[s][i];
        if(!dfn[t])
            tarjan(t,s),low[s]=min(low[s],low[t]);
        else
            if(vis[t]==2)
                low[s]=min(low[s],dfn[t]);
    }
    if(low[s]==dfn[s])
    {
        sum++;
        while(!sta.empty())
        {
            int t=sta.top();
            sta.pop();
            vis[t]=1;
            if(t==s)break;
        }
    }
}

 
void run()
{
    for(int i=1;i<=m;i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        gra[a].push_back(b);
    }
    for(int i=1;i<=n;i++)
        if(!dfn[i])
            tarjan(i,0);
    if(sum>1)
        cout<<"No"<<endl;
    else
        cout<<"Yes"<<endl;
}

 




Guess you like

Origin www.cnblogs.com/wengsy150943/p/10991204.html