Submission #752157

#TimeUsernameProblemLanguageResultExecution timeMemory
752157Dan4LifeConstruction of Highway (JOI18_construction)C++17
100 / 100
1450 ms106380 KiB
#include <bits/stdc++.h> using namespace std; #define pb push_back #define all(a) begin(a),end(a) const int N = (int)1e5+2; using ll = long long; using ar = array<int,2>; vector<int> adj[N]; deque<ar> ch[N], edge; int n, c[N], h[N], sz[N], p[N], dep[N], fen[N]; void upd(int x, int v){ for(; x<N; x+=x&-x) fen[x]+=v; } int sum(int x){ int s=0; for(; x; x-=x&-x) s+=fen[x]; return s; } int dfsSz(int s){ for(auto &u : adj[s]){ int x = adj[s][0]; dep[u] = dep[s]+1, sz[s]+=dfsSz(u); if(sz[x]<sz[u]) swap(adj[s][0],u); } return (sz[s]+=1); } void Hld(int s, int head){ h[s] = head; for(auto u : adj[s]) Hld(u,u==adj[s][0]?head:u); } ll calc(int a){ deque<ar> v, tv; v.clear(); ll ans = 0; while(a!=-1){ int H = h[a], siz = dep[a]-dep[h[a]]+1; tv.clear(); for(auto [x,cnt] : ch[H]){ tv.push_front({x,min(cnt,siz)}); siz-=min(cnt,siz); if(!siz) break; } a = p[H]; for(auto u : tv) v.pb(u); } for(int i = 1; i <= n; i++) fen[i]=0; for(auto [x,y] : v) ans+=(ll)y*sum(x-1), upd(x,y); return ans; } void add(int b, int v){ while(b!=-1){ int H = h[b], siz = dep[b]-dep[h[b]]+1; int tsz = siz; while(!ch[H].empty() and siz){ int cnt = ch[H].front()[1]; if(cnt<=siz) ch[H].pop_front(), siz-=cnt; else ch[H].front()[1]-=siz, siz=0; } ch[H].push_front({v,tsz}); b = p[H]; } } int main() { ios_base::sync_with_stdio(false); cin.tie(); cin >> n; vector<int> v; int a, b; p[1]=-1; for(int i = 1; i <= n; i++) cin >> c[i], v.pb(c[i]); sort(all(v)), v.erase(unique(all(v)),end(v)); for(int i = 1; i <= n; i++) c[i] = lower_bound(all(v),c[i])-begin(v)+1; for(int i = 1; i < n; i++) cin >> a >> b, adj[a].pb(b), p[b]=a, edge.pb({a,b}); ch[1].pb({c[1],1}); dfsSz(1); Hld(1,1); for(auto [a,b] : edge) cout << calc(a) << "\n", add(b,c[b]); }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...