尽力了,subtask #1 RE,应该是tarjan的问题,但是找不到
查看原帖
尽力了,subtask #1 RE,应该是tarjan的问题,但是找不到
22716
神仙酱楼主2024/5/5 19:02

基本想法是tarjan然后重新建图跑dfs,然而tarjan似乎RE了,我毫无头绪。玄关求条

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;

const int N = 110, M = N * N;
int h[N], hs[N], nxt[M], e[M], idx = 1;
int n, a, b, start_id, end_id;
int low[N], dfn[N], stmp, dcc;
bool is_cut[N], vis[N];
vector<int> cuts, dccs[N];
unordered_map<int, int> cut2id, id2cut;
stack<int> s;
void add(int h[], int a, int b) {
    e[idx] = b, nxt[idx] = h[a], h[a] = idx++;
}

void tarjan(int u, int root) {
    dfn[u] = low[u] = ++stmp;
    s.push(u);
    int child = 0;
    for (int i = h[u]; i; i = nxt[i]) {
        int j = e[i];
        if (!dfn[j]) {
            tarjan(j, root);
            low[u] = min(low[u], low[j]);
            child += u == root;
            if (low[j] >= dfn[u]) {
                is_cut[u] |= u != root || child > 1;
                int y;
                ++dcc;
                bool flag = false;
                auto check = [&](int x) {
                    if (x == a)
                        start_id = dcc;
                    if (x == b)
                        end_id = dcc;
                    if ((x == a || x == b) && exchange(flag, true)) {
                        puts("No solution");
                        exit(0);
                    }
                    dccs[dcc].push_back(x);
                };
                do {
                    y = s.top();
                    s.pop();
                    check(y);
                } while (y != j);
                check(u);
            }
        }
        else
            low[u] = min(low[u], dfn[j]);
    }
}

int dfs(int u) {
    vis[u] = true;
    if (u == end_id)
        return cuts.empty() ? -1 : *min_element(cuts.begin(), cuts.end());
    if (id2cut.count(u))
        cuts.push_back(id2cut[u]);
    for (int i = hs[u]; i; i = nxt[i]) {
        int j = e[i];
        if (!vis[j]) {
            int res = dfs(j);
            if (res != -1)
                return res;
        }
    }
    if (id2cut.count(u))
        cuts.pop_back();
    return -1;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen(".in", "r", stdin);
    // freopen(".out", "w", stdout);
#else
    cin.tie(0)->sync_with_stdio(0);
#endif
    scanf("%d", &n);
    while (scanf("%d %d\n", &a, &b) && a)
        add(h, a, b), add(h, b, a);
    scanf("%d %d", &a, &b);
    tarjan(a, a);
    for (int i = 1, j = 1; i <= n; ++i)
        if (is_cut[i])
            cut2id[i] = dcc + j++, id2cut[cut2id[i]] = i;
    for (int i = 1; i <= dcc; ++i)
        for (int nd : dccs[i]) {
            if (is_cut[nd])
                add(hs, cut2id[nd], i), add(hs, i, cut2id[nd]);
        }
    int ans = dfs(start_id);
    if (ans == -1)
        puts("No solution");
    else
        printf("%d", ans);
    return 0;
}
2024/5/5 19:02
加载中...