제출 #1264665

#제출 시각아이디문제언어결과실행 시간메모리
1264665tvgkCat Exercise (JOI23_ho_t4)C++20
100 / 100
178 ms47176 KiB
#include<bits/stdc++.h> using namespace std; #define task "a" #define se second #define fi first #define ll long long #define ii pair<ll, ll> const long mxN = 2e5 + 7; int n, h[mxN], par[mxN][30], a[mxN]; ll dsu[mxN]; vector<int> w[mxN]; void DFS(int j) { h[j] = h[par[j][0]] + 1; for (int i = 1; i <= 20; i++) par[j][i] = par[par[j][i - 1]][i - 1]; for (int i : w[j]) { if (h[i]) continue; par[i][0] = j; DFS(i); } } ll LCA(int u, int v) { ll res = h[u] + h[v]; if (h[u] < h[v]) swap(u, v); for (int i = 20; i >= 0; i--) { if (h[par[u][i]] >= h[v]) u = par[u][i]; } if (u == v) return res - h[u] * 2; for (int i = 20; i >= 0; i--) { if (par[u][i] != par[v][i]) { u = par[u][i]; v = par[v][i]; } } u = par[u][0]; return res - h[u] * 2; } int Find(int j) { if (dsu[j] <= 0) return j; else return dsu[j] = Find(dsu[j]); } void Union(int u, int v) { v = Find(v); dsu[u] = min(dsu[u], dsu[v] - LCA(u, v)); dsu[v] = u; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); //freopen(task".INP", "r", stdin); //freopen(task".OUT", "w", stdout); cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; u = a[u]; v = a[v]; w[u].push_back(v); w[v].push_back(u); } DFS(1); for (int i = 1; i <= n; i++) { for (int j : w[i]) { if (j < i) Union(i, j); } } cout << -dsu[n]; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...