Submission #167952

#TimeUsernameProblemLanguageResultExecution timeMemory
167952ThuleanxUntitled (POI11_rot)C++14
36 / 100
1083 ms9836 KiB
#include <bits/stdc++.h> using namespace std; const int N = 4e5+7; int n, t; int tree[N]; int l[N], r[N], lt[N], rt[N]; vector<int> p; long long ans; void add(int v, int x) { for (; v < N; v|=v+1) tree[v] += x; } int sum(int v) { int ans = 0; for (; v >= 0; v = (v&(v+1))-1) ans += tree[v]; return ans; } int dfs() { int x; cin>>x; if (x) { l[t] = r[t] = p.size(); p.push_back(x-1); } else { int left = dfs(), right = dfs(); l[t] = min(l[left], l[right]); r[t] = max(r[left], r[right]); lt[t] = left; rt[t] = right; } return t++; } void dfsSolve(int v, bool store) { if (l[v] == r[v]) { if (store) add(p[l[v]], 1); return; } if (r[rt[v]]-l[rt[v]] < r[lt[v]]-l[lt[v]]) swap(lt[v], rt[v]); dfsSolve(rt[v], 0); dfsSolve(lt[v], 1); long long res = 0; for (int x = l[rt[v]]; x <= r[rt[v]]; x++) res += sum(p[x]); ans += min(res, 1LL*(r[rt[v]]-l[rt[v]]+1)*(r[lt[v]]-l[lt[v]]+1)-res); if (store) for (int x = l[rt[v]]; x <= r[rt[v]]; x++) add(p[x], 1); else for (int x = l[lt[v]]; x <= r[lt[v]]; x++) add(p[x], -1); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; ans = t = 0; dfsSolve(dfs(), 0); cout << ans << endl; return 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...