首页 > 其他 > 详细

PAT T1008 Airline Routes

时间:2020-02-13 11:33:33      阅读:91      评论:0      收藏:0      [点我收藏+]

用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;
}

 

PAT T1008 Airline Routes

原文:https://www.cnblogs.com/zhanglichen/p/12302826.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!