虽然是模板但是却提醒我有向图一定要试着从每个点出发,不仅仅是因为图不一定连通,更有可能是只从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;
}
原文地址:https://www.cnblogs.com/Zolrk/p/9786244.html
时间: 2024-11-06 20:48:50