码迷,mamicode.com
首页 > 其他好文 > 详细

P1726 上白泽慧音 - 强连通分量模板

时间:2018-10-14 16:55:21      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:强连通分量   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 上白泽慧音 - 强连通分量模板

标签:强连通分量   algorithm   using   stack   efi   ++   name   tar   有向图   

原文地址:https://www.cnblogs.com/Zolrk/p/9786244.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!