87分,求优化方式

P2731 [USACO3.3] 骑马修栅栏 Riding the Fences

Owenzjg @ 2023-03-13 15:02:43

#include <bits/stdc++.h>
using namespace std;
int n, g[505][505], d[505], ans[505], st = -1;
bool flag;
int maxx;
int minn = -1;
void dfs(int x, int t) {
    // 从x往下搜,已经过t条边
    if (flag == true)
        return;
    ans[t] = x;
    if (t == n + 1) { // 每条边都经历过了
        flag = true;
        return;
    }
    for (int i = 1; i <= maxx; i++) {
        if (flag == true) {
            return;
        }
        if (g[x][i]) {
            // 枚举下一个点
            g[x][i]--;
            g[i][x]--;
            dfs(i, t + 1);
            g[x][i]++;
            g[i][x]++;
        }
    }
}
int main() {
    cin >> n;
    for (int i = 1, u, v; i <= n; i++) {
        cin >> u >> v;
        g[u][v]++;
        g[v][u]++;
        d[u]++;
        d[v]++;
        if (minn = -1)
            minn = u;
        maxx = max(maxx, max(u, v));
        minn = min(minn, min(u, v));
    }
    // 先统计每个点的度
    for (int i = 1; i <= maxx; i++) {
        if (d[i] % 2 == 1) {
            st = i;
            // 找最小奇点
            break;
        }
    }
    // 欧拉回路就从最小点出发
    if (st == -1) {
        st == minn;
    }
    dfs(st, 1);
    for (int i = 1; i <= n + 1; i++)
        cout << ans[i] << endl;
    // 经过n条边,总共是n+1个点
    return 0;
}

by Ice_lift @ 2023-05-23 10:19:32

void dfs(int u) {
    for (int v = 1; v <= 500; v++){
        if (g[u][v]){
            g[u][v]--,g[v][u]--;
            dfs(v);
        }   
    }
    path[++ans]=u;//存路径,记得倒着输出!
    return;
}

by ZeePing @ 2024-06-11 20:39:39

@Ice_lift 为什么这里一定要倒着存路径,不能在dfs一进来就输出结点号?


|