標籤:強連通分量 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 上白澤慧音 - 強連通分量模板