#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(x) begin(x), end(x)
#define sz(x) (int)x.size()
#define pb push_back
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T>
using index_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int maxn = 400001;
vector<int> adj[maxn];
int A[maxn];
index_set<int> T[maxn];
ll ans = 0LL;
void dfs(int s){
if(sz(adj[s]) == 0){
T[s].insert(A[s]);
return;
}
int u1 = adj[s][0], u2 = adj[s][1];
dfs(u1); dfs(u2);
if(sz(T[u1]) < sz(T[u2])) T[u1].swap(T[u2]);
int m1 = 0, m2 = 0;
for(auto e: T[u2]){
int x = T[u1].order_of_key(e);
m1 += x;
m2 += sz(T[u1])-x;
}
ans += (ll)min(m1, m2);
for(auto e: T[u2]){
T[u1].insert(e);
}
T[u2].clear();
T[s].swap(T[u1]);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n; cin >> n;
int cur = 0;
vector<int> v;
while(cur < n){
int x; cin >> x;
v.pb(x);
if(x != 0) cur++;
}
stack<int> s;
for(int i=1; i<=sz(v); i++){
int x = v[i-1];
if(!s.empty()){
adj[s.top()].pb(i);
}
s.push(i);
if(x != 0){
A[i] = x;
s.pop();
}
if(!s.empty() and sz(adj[s.top()]) == 2) s.pop();
}
dfs(1);
cout << ans;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
24 ms |
41052 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 |
24 ms |
41052 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
24 ms |
41308 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
30 ms |
41668 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
36 ms |
43992 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
146 ms |
58828 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Runtime error |
70 ms |
65536 KB |
Execution killed with signal 9 |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
59 ms |
51140 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Execution timed out |
1078 ms |
64676 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Execution timed out |
1022 ms |
62996 KB |
Time limit exceeded |
2 |
Halted |
0 ms |
0 KB |
- |