提供一组 hack & 请求加强数据
查看原帖
提供一组 hack & 请求加强数据
565040
Conan15楼主2025/2/7 10:51

数据:

4 3
a
b
c
d
a b
b c
c d

正确答案:

No Solution!

错误输出:

4
a
b
c
d
a

错误原因:

最后 dfs 求路径的时候出了一些问题,但是仍然能 AC。

错误代码:

#include <bits/stdc++.h>
using namespace std;
const int N = 70, M = 1e4 + 15, INF = 0x3f3f3f3f;
int n, m;
string s[N];
map<string, int> mp;
int in[N], out[N];

int h[N], e[M], c[M], w[M], ne[M], idx = 0;
void add(int a, int b, int x, int y) { e[idx] = b, c[idx] = x, w[idx] = y, ne[idx] = h[a], h[a] = idx++; }
void addedge(int a, int b, int x, int y) { add(a, b, x, y), add(b, a, 0, -y); }

int S, T;
int d[N], pre[N], Min[N];
bool st[N];
queue<int> q;

bool spfa() {
    while (q.size()) q.pop();
    for (int i = 1; i <= T; i++) d[i] = INF, Min[i] = pre[i] = 0, st[i] = 0;
    d[S] = 0, Min[S] = INF;
    q.push(S);
    while (q.size()) {
        int u = q.front(); q.pop();
        st[u] = 0;
        for (int i = h[u]; ~i; i = ne[i]) {
            if (!c[i]) continue;
            int v = e[i];
            if (d[v] > d[u] + w[i]) {
                d[v] = d[u] + w[i];
                Min[v] = min(Min[u], c[i]), pre[v] = i;
                if (!st[v]) st[v] = 1, q.push(v);
            }
        }
    }
    return Min[T] > 0;
}

void get() {
    int now = T, t = Min[T];
    while (now != S) {
        int id = pre[now];
        c[id] -= t, c[id ^ 1] += t;
        now = e[id ^ 1];
    }
}

void cost_flow() { while (spfa()) get(); }

bool vis[N];
int t[M], tot = 0;
void dfs(int u) {
    vis[u] = 1, t[++tot] = u - n;
    for (int i = h[u]; ~i; i = ne[i]) {
        if (c[i] > 0) continue;
        int v = e[i];
        if (vis[v + n]) continue;
        dfs(v + n); break;
    }
}

vector<string> ans;

int main() {
    memset(h, -1, sizeof h);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> s[i], mp[s[i]] = i;
        in[i] = i, out[i] = i + n;
        if (i == 1 || i == n) addedge(in[i], out[i], 2, -1);
        else addedge(in[i], out[i], 1, -1);
    }
    S = in[1], T = out[n];
    while (m--) {
        string a, b; cin >> a >> b;
        int u = mp[a], v = mp[b];
        addedge(out[u], in[v], 1, 0);
    }
    cost_flow();
    vis[1] = vis[n] = 0, tot = 0, dfs(out[1]);
    for (int i = 1; i <= tot; i++) ans.push_back(s[t[i]]);
    vis[1] = vis[n] = 0, tot = 0, dfs(out[1]);
    for (int i = tot; i >= 1; i--) ans.push_back(s[t[i]]);
    if (ans.size() == 2) return puts("No Solution!"), 0;
    cout << ans.size() - 1 << endl;
    for (string it : ans) cout << it << endl;
    return 0;
}
2025/2/7 10:51
加载中...