# LuoguP5290 [十二省联考2019]春节十二响 | 启发式合并

## 代码

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#define space putchar(' ')
#define enter putchar('\n')
using namespace std;
typedef long long ll;
template <class T>
bool op = 0;
char c;
while(c = getchar(), c < '0' || c > '9')
if(c == '-') op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op) x = -x;
}
template <class T>
void write(T x){
if(x < 0) putchar('-'), x = -x;
if(x >= 10) write(x / 10);
putchar('0' + x % 10);
}

const int N = 200005;
int n, id[N];
ll w[N], ans;
vector <int> son[N];
priority_queue <int> que[N];

bool cmp(int a, int b){
return que[id[a]].size() > que[id[b]].size();
}
void dfs(int u){
vector <int> buf;
for(auto v: son[u])
dfs(v);
sort(son[u].begin(), son[u].end(), cmp);
for(auto v: son[u]){
if(que[id[u]].empty()) swap(id[u], id[v]);
else{
while(!que[id[v]].empty()){
int u_top = que[id[u]].top(), v_top = que[id[v]].top();
que[id[u]].pop(), que[id[v]].pop();
buf.push_back(max(u_top, v_top));
}
for(auto x: buf)
que[id[u]].push(x);
buf.clear();
}
}
que[id[u]].push(w[u]);
}

int main(){