POJ 2762 Going from u to v or from v to u? / 強連通分量&&拓撲

來源:互聯網
上載者:User

給你一張圖 判斷是否任意2點u,v 滿足要麼u->v 可達 或者 v->u 可達 相互可達也可以

強連通分量縮點 在做拓撲 拓撲唯一 說明都互相可達

有空放棄用矩陣表示的拓撲 浪費時間 浪費空間

#include <cstdio>#include <cstring>#include <vector>#include <stack>#include <algorithm>using namespace std;const int maxn = 1010;vector <int> G[maxn];int pre[maxn];int low[maxn];int sccno[maxn];int dfs_clock;int scc_cnt;stack <int> S;int n, m;int degree[maxn];int cnt[maxn];int Topo[maxn][maxn];void dfs(int u){pre[u] = low[u] = ++dfs_clock;S.push(u);for(int i = 0; i < G[u].size(); i++){int v = G[u][i];if(!pre[v]){dfs(v);low[u] = min(low[u], low[v]);}else if(!sccno[v])low[u] = min(low[u], pre[v]);}if(pre[u] == low[u]){scc_cnt++;while(1){cnt[scc_cnt]++;int x = S.top();S.pop();sccno[x] = scc_cnt;if(x == u)break;}}}void find_scc(){dfs_clock = scc_cnt = 0;memset(sccno, 0, sizeof(sccno));memset(pre, 0, sizeof(pre));memset(cnt, 0, sizeof(cnt));for(int i = 1; i <= n; i++)if(!pre[i])dfs(i);}bool topo(){for(int i = 1; i <= scc_cnt; i++){int ans = 0;for(int j = 1; j <= scc_cnt; j++){if(!degree[j])ans++;if(ans > 1)return false;}for(int j = 1; j <= scc_cnt; j++){if(!degree[j]){degree[j]--;for(int k = 1; k <= scc_cnt; k++){if(Topo[k][j])degree[k]--;}break;}}}return true;}int main(){int T;scanf("%d", &T);while(T--){scanf("%d %d", &n, &m);for(int i = 1; i <= n; i++)G[i].clear();while(m--){int u, v;scanf("%d %d", &u, &v);G[u].push_back(v);}find_scc();memset(degree, 0, sizeof(degree));memset(Topo, 0, sizeof(Topo));for(int i = 1; i <= n; i++){for(int j = 0; j < G[i].size(); j++){int v = G[i][j];if(sccno[i] != sccno[v]){degree[sccno[i]]++;Topo[sccno[i]][sccno[v]] = 1;}}}if(topo())printf("Yes\n");elseprintf("No\n");}return 0;}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.