Submission #1020665

#TimeUsernameProblemLanguageResultExecution timeMemory
1020665fimhUntitled (POI11_rot)C++17
100 / 100
216 ms16748 KiB
#include <bits/stdc++.h> // #include "D:/debug.h" using namespace std; const int MAXN = 4e6 + 5; // #define int long long int n; int g[MAXN][2]; int sz[MAXN]; long long dp[MAXN]; int a[MAXN]; struct fenwick_tree { int bit[MAXN + 5]; void update(int pos, int v) { while(pos <= n) { bit[pos] += v; pos += (pos & (-pos)); } } int get(int pos) { int ans = 0; while(pos) { ans += bit[pos]; pos -= (pos & (-pos)); } return ans; } int getR(int l, int r){ return get(r) - get(l - 1); } } ft; int tdfs = 0, cnt = 0; void build_tree(int u) { for(int i=0; i<2; i++) { int x; cin>>x; if(x == 0) { tdfs++; g[u][i] = tdfs; build_tree(tdfs); } else { tdfs++; g[u][i] = tdfs; a[tdfs] = x; cnt++; } if(cnt == n) return; } } void calsz(int u){ sz[u] = 1; for(int i = 0; i < 2; i++){ if(g[u][i] != 0) calsz(g[u][i]), sz[u] += sz[g[u][i]]; } } void mod(int u, int val){ if(a[u] != 0) ft.update(a[u], val); for(int i = 0; i < 2; i++) if(g[u][i] != 0) mod(g[u][i], val); } long long c1, c2; void cal(int u){ if(a[u] != 0){ c1 += ft.get(a[u] - 1); c2 += ft.getR(a[u] + 1, n); } for(int i = 0; i < 2; i++) if(g[u][i] != 0) cal(g[u][i]); } void dfs(int u){ int bc = 0; for(int i = 0; i < 2; i++){ if(sz[g[u][i]] > sz[bc]) bc = g[u][i]; } for(int i = 0; i < 2; i++) if(g[u][i] != bc && g[u][i] != 0) dfs(g[u][i]), dp[u] += dp[g[u][i]], mod(g[u][i], -1); if(bc) dfs(bc), dp[u] += dp[bc]; if(a[u] != 0) ft.update(a[u], 1); c1 = 0, c2 = 0; for(int i = 0; i < 2; i++) if(g[u][i] != bc && g[u][i] != 0) cal(g[u][i]); dp[u] += min(c1,c2); for(int i = 0; i < 2; i++) if(g[u][i] != bc && g[u][i] != 0) mod(g[u][i], 1); } int main(){ cin >> n; build_tree(0); calsz(1); dfs(1); cout << dp[1]; }
#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...