제출 #947806

#제출 시각아이디문제언어결과실행 시간메모리
947806pccConstruction of Highway (JOI18_construction)C++17
100 / 100
289 ms87240 KiB
#include <bits/stdc++.h> using namespace std; #define ll long long #define pll pair<ll,ll> #define pii pair<int,int> #define fs first #define sc second #define tiii tuple<int,int,int> #define tlll tuple<ll,ll,ll> const int mxn = 1e5+10; vector<int> tree[mxn]; int link_top[mxn],sz[mxn],bs[mxn],idx[mxn],par[mxn],dep[mxn]; int N; int arr[mxn]; vector<pii> req; deque<tiii> dq[mxn]; int cnt = 0; int dfs1(int now){ sz[now] = 1; for(auto nxt:tree[now]){ par[nxt] = now; dep[nxt] = dep[now]+1; sz[now] += dfs1(nxt); if(!bs[now]||sz[nxt]>sz[bs[now]])bs[now] = nxt; } return sz[now]; } void dfs2(int now,int top){ dq[top].push_back(tiii(dep[now],dep[now],arr[now])); link_top[now] = top; idx[now] = ++cnt; if(bs[now])dfs2(bs[now],top); for(auto nxt:tree[now]){ if(nxt == bs[now])continue; dfs2(nxt,nxt); } return; } struct BIT{ int bit[mxn]; BIT(){ memset(bit,0,sizeof(bit)); } void modify(int p,int v){ for(;p<mxn;p+=p&-p)bit[p] += v; return; } ll getval(int p){ ll re = 0; for(;p>0;p-= p&-p)re += bit[p]; return re; } }; BIT bit; ll get_inv(vector<pii> &v){ ll re = 0; for(auto &i:v){ re += 1ll*i.fs*bit.getval(i.sc-1); bit.modify(i.sc,i.fs); } for(auto &i:v){ bit.modify(i.sc,-(bit.getval(i.sc)-bit.getval(i.sc-1))); } return re; } void calc(int a,int b){ vector<pii> vv; int now = a; //cerr<<"CALC:"<<a<<','<<b<<":"<<endl; while(now){ vector<pii> v; int tp = link_top[now]; int st = get<0>(dq[tp].front()); //cerr<<now<<' '<<tp<<":";for(auto &[a,b,c]:dq[tp])cerr<<a<<' '<<b<<' '<<c<<','; //cerr<<endl; while(!dq[tp].empty()){ auto &[s,e,val] = dq[tp].front(); if(s>dep[now])break; v.push_back(pii(min(e,dep[now])-s+1,val)); if(e>dep[now]){ s = dep[now]+1; break; } dq[tp].pop_front(); } dq[tp].push_front(tiii(st,dep[now],arr[b])); now = par[tp]; for(auto it = v.rbegin();it != v.rend();it++)vv.push_back(*it); } //cerr<<"V:";for(auto [a,b]:vv)cerr<<a<<' '<<b<<',';cerr<<endl; cout<<get_inv(vv)<<'\n'; return; } vector<int> all; int main(){ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); cin>>N; all.push_back(0); for(int i = 1;i<=N;i++){ cin>>arr[i]; all.push_back(arr[i]); } sort(all.begin(),all.end());all.resize(unique(all.begin(),all.end())-all.begin()); for(int i = 1;i<=N;i++){ arr[i] = lower_bound(all.begin(),all.end(),arr[i])-all.begin(); } for(int i = 1;i<N;i++){ int a,b; cin>>a>>b; tree[a].push_back(b); req.push_back({a,b}); } dfs1(1); dfs2(1,1); for(auto &i:req)calc(i.fs,i.sc); }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...