很久没打Tarjan,回来复习,结果40pts,不知道为啥错了,求调
查看原帖
很久没打Tarjan,回来复习,结果40pts,不知道为啥错了,求调
464528
见贤思齐_Seakies楼主2023/1/19 17:19
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e3 + 9;
const int MAXM = 5e4 + 9;
struct Edge {
    int to, nxt;
} e[MAXM * 2];
int h[MAXN], cnt;
void addedge(int u, int v) {
    e[cnt].to = v, e[cnt].nxt = h[u], h[u] = cnt++;
}
int n, m;
int tot, dfn[MAXN], low[MAXN], in_stk[MAXN], s[MAXN], top;
priority_queue<int, vector<int>, greater<int> > scc[MAXN];
int color[MAXN], sz[MAXN], scc_cnt, max_scc;
void Tarjan(int u) {
    dfn[u] = low[u] = ++tot;
    in_stk[u] = 1, s[++top] = u;
    for (int i = h[u]; ~i; i = e[i].nxt) {
        int v = e[i].to;
        if (!dfn[v]) {
            Tarjan(v);
            low[u] = min(low[u], low[v]);
        } else if (in_stk[v]) low[u] = min(low[u], dfn[v]);
    }
    if (low[u] == dfn[u]) {
        scc_cnt++;
        while (s[top + 1] != u) {
            color[s[top]] = scc_cnt;
            scc[scc_cnt].push(s[top--]);
            sz[scc_cnt]++;
        }
        max_scc = max(max_scc, sz[scc_cnt]);
    }
}
int main() {
    memset(h, -1, sizeof(h));
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int a, b, t;
        cin >> a >> b >> t;
        if (t == 1) addedge(a, b);
        else if (t == 2) {
            addedge(a, b);
            addedge(b, a);
        }
    }
    for (int i = 1; i <= n; i++)
        if (!dfn[i])
            Tarjan(i);
    cout << max_scc << endl;
    for (int i = 1; i <= n; i++) {
        if (sz[color[i]] == max_scc) {
            while (!scc[color[i]].empty()) {
                cout << scc[color[i]].top() << ' ';
                scc[color[i]].pop();
            }
            break;
        }
    }
    cout << endl;
    return 0;
}
2023/1/19 17:19
加载中...