基环树问题 解题报告

发布时间 2023-08-30 12:21:37作者: ancer

luogu P5022 旅行

题意

对于60%的数据,给一棵树,求一条字典序最小的Hamilton路径;
对于40%的数据,给一颗基环树,求一条字典序最小的Hamilton路径。

分析

前向星存图,对于每个点的出边排序,从1开始dfs一遍即可过60%数据;
对于基环树,由于Hamilton路径在树上必然有一条边不经过,而这条边必然在环上,
可以考虑枚举删除环上的边,遍历图找出并更新答案。
然而题目数据m就5000,枚举每条边都删一下也可行。

代码

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define rg register
#define IOS ios::sync_with_stdio(false);cin.tie(NULL),cout.tie(NULL)
/*inline int read(){
    rg int x = 0, f = 1;
    rg char c = getchar();
    while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
    while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
    return x * f;
}*/
const int N = 5e3 + 7;
int n, m;
vector<vector<int> > G(N);
struct edge{
    int u, v;
}e[N];

void dfs1(int u, int fa){
    cout << u << " ";
    for (auto v : G[u]){
        if (v == fa) continue;
        dfs1(v, u);
    }
}
int ans[N], res[N];
int cnt, delnum;
bool vis[N];

inline bool check(int u, int v){
    if (e[delnum].u == u && e[delnum].v == v || e[delnum].u == v && e[delnum].v == u) return true;
    return false;
}
void dfs2(int u, int fa){
    res[++cnt] = u;
    vis[u] = true;
    for (auto v : G[u]){
        if (vis[v] || check(u, v)) continue;
        dfs2(v, u);
    }
}
inline bool cmp(){
    for (int i(1); i <= n; ++i)
        if (ans[i] != res[i])
            return ans[i] > res[i];
    return false;
}
int main(){
    IOS;
    //freopen("in.txt", "r", stdin);
    cin >> n >> m;
    for (int i(1); i <= m; ++i){
        int u, v; cin >> u >> v;
        G[u].push_back(v), G[v].push_back(u);
        e[i].u = u, e[i].v = v;
    }
    for (int i(1); i <= n; ++i)
        sort(G[i].begin(), G[i].end());
    if (m == n - 1)
        dfs1(1, 0);
    else {
        memset(ans, 0x3f, sizeof(ans));
        for (int i(1); i <= m; ++i){
            memset(res, 0, sizeof(res));
            memset(vis, 0, sizeof(vis));
            cnt = 0;
            delnum = i;
            dfs2(1, 0);
            if (cmp() && cnt == n)
                for (int i(1); i <= n; ++i)
                    ans[i] = res[i];
        }
        for (int i(1); i <= n; ++i) cout << ans[i] << " ";
    }

    return 0;
}