题解:CF1508E Tree Calendar
Priestess_SLG · · 题解
::::info[性质
:::success[证明]
记
::::info[性质
::::info[性质
根据性质
天数即执行的操作数是容易求的,根据上面给出的性质可知答案就是
#pragma GCC optimize(3, "Ofast", "inline", "unroll-loops")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define int long long
using namespace std;
const int N = 300010;
const int inf = 1e18;
const int mod = 998244353;
vector<int> adj[N];
int a[N], e[N], dfn[N], odfn[N], idx, idx2, dep[N], up[N], pdf[N], siz[N];
inline void dfs(int u, int fa) {
dfn[u] = ++idx, dep[u] = dep[fa] + 1, up[u] = fa, siz[u] = 1;
for (int &v : adj[u]) if (v != fa) dfs(v, u), siz[u] += siz[v];
odfn[u] = ++idx2, pdf[idx2] = u;
}
inline void sol() {
int n; cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
for (int i = 1; i < n; ++i) {
int a, b; cin >> a >> b;
adj[a].emplace_back(b), adj[b].emplace_back(a);
}
for (int i = 1; i <= n; ++i)
sort(adj[i].begin(), adj[i].end(), [&](auto &l, auto &r) { return a[l] < a[r]; });
function<bool(int)> chk_leaf = [&](int u) {
return u != 1 && adj[u].size() == 1;
};
function<bool(int, int)> chk_ance = [&](int u, int v) {
return dfn[u] <= dfn[v] && dfn[v] < dfn[u] + siz[u];
};
dep[0] = -1, dfs(1, 0);
for (int i = 1; i <= n; ++i) e[a[i]] = i;
int id = a[1] - 1;
if (a[1] == 1) {
for (int i = 1; i <= n; ++i)
if (a[i] != dfn[i]) { cout << "NO\n"; return; }
cout << "YES\n0\n";
for (int i = 1; i <= n; ++i) cout << a[i] << ' ';
cout << '\n';
} else {
for (int i = 1; i <= n; ++i)
if (a[i] < id && a[i] != odfn[i]) { cout << "NO\n"; return; }
if (!chk_ance(e[id], pdf[id])) { cout << "NO\n"; return; }
int cnt = 0;
for (int i = 1; i <= n; ++i)
if (a[i] < id) cnt += dep[i];
int tmp = -1;
for (int i = 1; i <= n; ++i) if (a[i] == id) { tmp = i; break; }
while (tmp > 1) ++cnt, swap(a[tmp], a[up[tmp]]), tmp = up[tmp];
for (int i = 2; i <= n; ++i)
if (a[i] >= id && a[up[i]] > a[i]) { cout << "NO\n"; return; }
cout << "YES\n";
cout << cnt << '\n';
for (int i = 1; i <= n; ++i) cout << dfn[i] << ' ';
cout << '\n';
}
}
signed main() {
cin.tie(0)->sync_with_stdio(false);
cout << fixed << setprecision(15);
sol();
// int T; cin >> T; while (T--) sol();
return 0;
}