#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
vector<int> adj[400008];
ordered_set _list[400008];
long long inv[400008];
void add_edge(int u, int v) {adj[u].push_back(v);}
int n, tmp, counter;
void input(int id) {
cin >> tmp;
if (tmp) add_edge(id, tmp), _list[tmp].insert(-tmp);
else add_edge(id, ++counter), input(counter);
cin >> tmp;
if (tmp) add_edge(id, tmp), _list[tmp].insert(-tmp);
else add_edge(id, ++counter), input(counter);
}
void DFS(int u, int p) {
int mn_L = -1, mn_R = -1; vector<int> C;
for (int v : adj[u]) if (v != p) {
// cout << u << " -> " << v << '\n';
if (v > n) DFS(v, u);
inv[u] += inv[v]; C.push_back(v);
if (C.size() == 1) mn_L = *prev(_list[v].end());
else mn_R = *prev(_list[v].end());
}
inv[u] += min(_list[C[1]].order_of_key(mn_L), _list[C[0]].order_of_key(mn_R));
for (int v : adj[u]) if (v != p) {
if (_list[u].size() < _list[v].size()) _list[u].swap(_list[v]);
for (int item : _list[v]) _list[u].insert(item);
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n >> tmp; counter = n + 1;
if (tmp == 1) {cout << 0; return 0;}
input(n + 1); DFS(n + 1, 0); cout << inv[n + 1];
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
25 ms |
40968 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
28 ms |
41048 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
26 ms |
41300 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
31 ms |
42072 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
38 ms |
44216 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
107 ms |
58964 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
126 ms |
64848 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
180 ms |
64964 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
114 ms |
65536 KB |
Execution killed with signal 9 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
154 ms |
65536 KB |
Execution killed with signal 9 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
155 ms |
65536 KB |
Execution killed with signal 9 |
2 |
Halted |
0 ms |
0 KB |
- |