Submission #1020559

#TimeUsernameProblemLanguageResultExecution timeMemory
1020559BuzzyBeezUntitled (POI11_rot)C++17
72 / 100
206 ms65536 KiB
#include <bits/stdc++.h> using namespace std; const int N = 4e5; int a[N + 8]; int adj[N + 8][2]; set<int> _list[N + 8]; int sz[N + 8]; int n, tmp, id = 1, x; void input() { cin >> x; if (x) {_list[id].insert(x); ++sz[id]; a[id] = x; return;} int t = id; adj[t][0] = id + 1; ++id; input(); adj[t][1] = id + 1; ++id; input(); } void DFS_sz(int u, int p) { if (adj[u][0] == 0) return; DFS_sz(adj[u][0], u); sz[u] += sz[adj[u][0]]; DFS_sz(adj[u][1], u); sz[u] += sz[adj[u][1]]; } struct Binary_Indexed_Tree { vector<int> BIT; Binary_Indexed_Tree() {BIT.assign(N / 2 + 8, 0);} int pt; void update(int u, int v) { pt = u; while (pt <= N / 2) { BIT[pt] += v; pt += pt & -pt; } } int res; int pf(int p) { if (p <= 0) return 0; res = 0; pt = p; while (pt) { res += BIT[pt]; pt -= pt & -pt; } return res; } int range(int l, int r) { if (l > r) return 0; return pf(r) - pf(l - 1); } } tree; int costLR, costRL; long long DFS(int u, int p) { long long res = 0; if (sz[u] > 1) { int L = adj[u][0], R = adj[u][1]; if (sz[L] < sz[R]) swap(L, R); // cout << u << " -> " << R << endl; res += DFS(R, u); for (int item : _list[R]) tree.update(item, -1); // cout << u << " -> " << L << endl; res += DFS(L, u); costLR = costRL = 0; for (int item : _list[R]) costLR += tree.range(item + 1, n), costRL += tree.range(1, item - 1); res += min(costLR, costRL); for (int item : _list[R]) tree.update(item, +1); for (int v : {L, R}) { if (_list[u].size() < _list[v].size()) swap(_list[u], _list[v]); for (int item : _list[v]) _list[u].insert(item); } } if (a[u]) tree.update(a[u], +1); return res; } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n; input(); DFS_sz(1, 0); cout << DFS(1, 0); }
#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...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...