POJ 3180-The Cow Prom (圖論-有向圖強聯通tarjan演算法)

來源:互聯網
上載者:User

標籤:

題目大意:有n個牛在一塊, m條單項繩子, 有m個連結關係, 問有多少個團體內部任意兩頭牛可以相互可達

解題思路:有向圖強連通分量模版圖

代碼如下:

#include<stdio.h>#include<vector>#include<map>#include<set>#include<algorithm>using namespace std;typedef long long ll;const int N = 10003;vector<int>G[N], DQ;int low[N], dfn[N], tot;bool mk[N];int n, m, ans;void init(){    ans = tot = 0;    DQ.clear();    for(int i=1; i<=n; ++ i)    {        G[i].clear();        low[i] = dfn[i] = -1;        mk[i] = false;    }}void tarjan(int u, int f){    dfn[u] = low[u] = ++ tot;    DQ.push_back(u);    mk[u] = true;    for(int i = 0; i<G[u].size(); ++ i)    {        int v = G[u][i];        if(dfn[v] == -1)        {            tarjan(v, u);            low[u] = min(low[u], low[v]);        }        else if(mk[v])            low[u] = min(low[u], dfn[v]);    }    if(dfn[u] == low[u])    {        int s;        int k = 0;        do        {            s = DQ.back();            k ++;            DQ.pop_back();            mk[s] = false;        }        while(u != s);        if(k > 1)            ans ++;    }}void solve(){    for(int i=1; i<=n; ++ i)    {        if(dfn[i] == -1)            tarjan(i, -1);    }    printf("%d\n", ans);}int main(){    while(~scanf("%d%d", &n, &m))    {        init();        for(int i=1; i<=m; ++ i)        {            int u, v;            scanf("%d%d", &u, &v);            G[u].push_back(v);        }        solve();    }    return 0;}
View Code

 

POJ 3180-The Cow Prom (圖論-有向圖強聯通tarjan演算法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.