解题:贪心
很明显越靠近越好。随便从一个点出发,按照翻的排列方式来选择和父亲链接还是和兄弟链接。记得每次加2哦~~~~
具体代码:
#include<bits/stdc++.h> using namespace std; #define int long long const int N = 1e5 + 500; int n, par[N], swp[N], p[N]; vector<int>g[N], rev; void dfs(int a, int pp) { rev.push_back(a); par[a] = pp; for (auto& x : g[a]) { if (x == pp)continue; dfs(x, a); } } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for (int i = 0; i < n - 1; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } for (int i = 1; i <= n; i++) p[i] = i; dfs(1, 0); reverse(rev.begin(), rev.end()); int ans = 0; for (int i = 0; i < n; i++) { int u = rev[i]; if (!swp[u]) { int up = par[u]; if (par[u] == 0) up = g[u][0]; swp[u] = swp[up] = 1; swap(p[u], p[up]); ans += 2; } } cout << ans << '\n'; for (int i = 1; i <= n; i++) cout << p[i] << ' '; cout << '\n'; }
标签:村子,pp,int,rev,back,cin,push,最小化 From: https://www.cnblogs.com/yonglicp/p/17541732.html