#include <bits/stdc++.h>
using namespace std;
const int maxn = 4005;
int a[maxn];
vector<int> adj[maxn];
int par[maxn];
int h[maxn];
int n;
int inv[maxn];
vector<pair<int, int>> q;
int fen[maxn][maxn];
vector<int> comp;
vector<int> way[maxn];
int ans;
void compress(){
for (int i=1; i<=n; i++) comp.push_back(a[i]);
sort(comp.begin(), comp.end());
for (int i=1; i<=n; i++) a[i] = lower_bound(comp.begin(), comp.end(), a[i]) - comp.begin() + 1;
}
void findpar(int node, int parent){
h[node] = h[parent] + 1;
par[node] = parent;
for (int x: way[parent]) way[node].push_back(x);
way[node].push_back(node);
for (int x: adj[node]){
if (x != parent){
findpar(x, node);
}
}
}
void update(int node, int val){
while (node != 1){
a[node] = val;
node = par[node];
}
a[1] = val;
}
void updatefen(int index, int t){
while (index <= comp.size()){
fen[t][index]++;
index += (index & (-index));
}
}
int queryfen(int index, int t){
int res = 0;
while (index > 0){
res += fen[t][index];
index -= (index & (-index));
}
return res;
}
void build(int node){
for (int i=1; i<=n; i++) fen[node][i] = 0;
for (int x: way[node]){
updatefen(a[x], node);
}
inv[node] = inv[par[node]] + queryfen(comp.size(), node) - queryfen(a[node], node);
}
void dfs(int node){
build(node);
for (int x: adj[node]){
if (x == par[node]) continue;
dfs(x);
}
}
int main()
{
ios_base :: sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for (int i=1; i<=n; i++) cin >> a[i];
for (int i=1; i<n; i++){
int x, y;
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
q.push_back({x, y});
}
compress();
findpar(1, 0);
dfs(1);
for (int i=0; i<n-1; i++){
int x = q[i].first, y = q[i].second;
if (h[x] > h[y]) swap(x, y);
cout << inv[x] << '\n';
update(y, a[y]);
dfs(1);
}
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... |