PAT T1008 Airline Routes

用tarjan算法缩点~

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+14;
vector<int> g[maxn];
int N,M,x,y;
int low[maxn];
int dfn[maxn];
int cnt;
int pos[maxn];
int scc;
stack<int> st;
void tarjan (int x) {
    low[x]=dfn[x]=++cnt;
    st.push(x);
    for (int i=0;i<g[x].size();i++) {
        if (!low[g[x][i]]) {
            tarjan (g[x][i]);
            low[x]=min(low[x],low[g[x][i]]);
        }
        else if (!pos[g[x][i]]) low[x]=min(low[x],dfn[g[x][i]]);
    }
    if (low[x]==dfn[x]) {
        scc++;
        while (1) {
            int u=st.top();
            st.pop();
            low[u]=low[x];
            pos[u]=scc;
            if (u==x) break;
        }
    }
}
int main () {
    scanf ("%d %d",&N,&M);
    for (int i=0;i<M;i++) {
        scanf ("%d %d",&x,&y);
        g[x].push_back(y);
    }
    for (int i=1;i<=N;i++) 
    if (!low[i]) tarjan(i);
    scanf ("%d",&M);
    for (int i=0;i<M;i++) {
        scanf ("%d %d",&x,&y);
        printf ("%s\n",low[x]==low[y]?"Yes":"No");
    }
    return 0;
}

 

posted @ 2020-02-13 11:27  zlc0405  阅读(131)  评论(0编辑  收藏  举报