P1726 上白澤慧音 - 強連通分量模板

來源:互聯網
上載者:User

標籤:強連通分量   algorithm   using   stack   efi   ++   name   tar   有向圖   

雖然是模板但是卻提醒我有向圖一定要試著從每個點出發,不僅僅是因為圖不一定連通,更有可能是只從1號點出發哪也去不了的情況

#include <algorithm>#include <iostream>#include <cstring>#include <cstdio>#include <stack>using namespace std;#define debug(x) cerr << #x << "=" << x << endl;const int MAXN = 10000 + 10;stack<int> s;int n,m,vis[MAXN],last[MAXN],edge_tot,temp[MAXN],fina[MAXN],ans,dfn[MAXN],low[MAXN],flg[MAXN],cnt;struct Edge{    int u, v, w, to;    Edge(){}    Edge(int u, int v, int to) : u(u), v(v), to(to) {}}e[50001 * 2];inline void add(int u, int v) {    e[++edge_tot] = Edge(u, v, last[u]);    last[u] = edge_tot; }bool cmp(int a, int b) {    return a < b;}void tarjan(int x) {    dfn[x] = low[x] = ++cnt;    s.push(x);    flg[x] = true;    for(int i=last[x]; i; i=e[i].to) {        int v = e[i].v;        if(!dfn[v]) {            tarjan(v);            if(low[v] < low[x]) low[x] = low[v];        } else if(dfn[v] < low[x] && flg[v]) {            low[x] = dfn[v];        }    }    if(dfn[x] == low[x]) {        int j, num=0;        do{            j = s.top();            s.pop();            temp[++num] = j;             flg[j] = 0;        }while(j != x);        sort(temp+1, temp+num+1, cmp);        if(num > ans) {            memcpy(fina, temp, sizeof(temp));            ans = num;        } else if(num == ans) {            if(memcmp(fina, temp, sizeof(temp)) > 0)                 memcpy(fina, temp, sizeof(temp));        }    }    }int main() {    scanf("%d%d", &n, &m);    for(int i=1; i<=m; i++) {        int a,b,t;        scanf("%d%d%d",&a, &b, &t);        add(a, b);        if(t == 2) add (b, a);    }    for(int i=1; i<=n; i++)         if(!dfn[i]) //關鍵之處            tarjan(i);    printf("%d\n", ans);    for(int i=1; i<=ans; i++) {        printf("%d ", fina[i]);    }    return 0;} 

P1726 上白澤慧音 - 強連通分量模板

聯繫我們

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