/* Author : Mychecksdead */
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD (1000000000+7)
#define MOD1 (998244353)
#define pb push_back
#define all(x) x.begin(), x.end()
#define en cout << '\n'
#define ff first
#define ss second
#define pii pair<int,int>
#define vi vector<int>
const int N = 1e6+100, M = 1e5+10, K = 52, MX = 30;
struct Fenwick{
int n;
vector<int> t;
Fenwick(int _n){
n = _n;
t.resize(n+1, 0);
}
void add(int v, int val){
while(v <= n){
t[v]+=val;
v += (v&-v);
}
}
ll get(int v){
ll res = 0;
while(v > 0){
res += t[v];
v -= (v&-v);
}
return res;
}
};
int n, c[N], par[N], tin[N], heavy[N], sz[N], timer = 1, tout[N];
vector<array<int, 2>> a;
vi g[N];
set<pii> S[N];
Fenwick fw(N);
void pre(int v){
sz[v] = 1;
for(int &u: g[v]){
pre(u);
sz[v] += sz[u];
if(sz[u] > sz[g[v][0]]) swap(g[v][0], u);
}
}
void dfs(int v){
tin[v] = timer++;
for(int u: g[v]){
par[u] = v;
if(u == g[v][0]) heavy[u] = heavy[v];
else heavy[u] = u;
dfs(u);
}
tout[v] = timer - 1;
}
void add(int v, int val){
// begin at v, go up, while doing it add {tin[v], val}
while(true){
int t = heavy[v];
while(S[t].size() && (*S[t].begin()).ff <= tin[v]){
S[t].erase(S[t].begin());
}
if(S[t].empty() || (*S[t].begin()).ss != val){
S[t].insert({tin[v], val});
}
if(heavy[v] == 1) break;
v = par[heavy[v]];
}
}
ll calc(int v){
ll res = 0;
// begin at v, while going up calculate via fenwick
vector<pii> used;
// cerr << v << " her\n";
int vv = v;
while(true){
int t = heavy[v];
auto it = S[t].lower_bound(pii{tin[v] - (v == vv), -1});
// cerr << v << '\n';
// for(auto [x, y]: S[t]) cerr << x << ' ' << y << ',';
// cerr << '\n';
// cerr << '\n';
if(S[t].size()){
if(it == S[t].end()) --it;
int cur = tin[v] - (vv == v);
while(true){
int nxt = (it == S[t].begin() ? tin[heavy[v]] - 1 : (*prev(it)).ff);
int cnt = cur - nxt;
used.pb({(*it).ss, cnt});
res += fw.get((*it).ss - 1) * cnt;
fw.add((*it).ss, cnt);
if(it == S[t].begin()) break;
--it;
cur = nxt;
}
}
if(heavy[v] == 1) break;
v = par[heavy[v]];
}
for(auto [x, y]: used) fw.add(x, -y);
return res;
}
void solve(){
cin >> n;
vi val;
for(int i = 1; i <= n; ++i){
cin >> c[i];
val.pb(c[i]);
}
for(int i = 1; i < n; ++i){
int u, v; cin >> u >> v;
a.pb({u, v});
g[u].pb(v);
}
sort(all(val));
for(int i = 1; i <= n; ++i){
c[i] = lower_bound(all(val), c[i]) - val.begin() + 1;
}
pre(1);
heavy[1] = 1;
dfs(1);
add(1, c[1]);
for(auto [u, v]: a){
cout << calc(v) << '\n';
add(v, c[v]);
}
}
int main(){
cin.tie(0); ios::sync_with_stdio(0);
int tt = 1, aa;
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(tt--){
solve();
en;
}
cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" seconds\n";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |