[51nod][cf468D]1558 树中的配对

时间:2023-12-12 08:42:44

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1558

不是很懂dalao们用线段树是怎么写的……

反正找出重心以后每个子树一个堆,再来个全局堆就吼了

#include<queue>
#include<stdio.h>
#include<algorithm>
#define MN 100001
using namespace std; int read_p,read_ca;
inline int read(){
read_p=;read_ca=getchar();
while(read_ca<''||read_ca>'') read_ca=getchar();
while(read_ca>=''&&read_ca<='') read_p=read_p*+read_ca-,read_ca=getchar();
return read_p;
}
struct na{int y,z,ne;}b[MN<<];
struct ma{int x,y;ma(int _x=,int _y=):x(_x),y(_y){}};
bool operator < (ma a,ma b){return a.x<b.x;}
priority_queue<ma> q[MN],Q,_q;
int n,m,l[MN],x,y,z,ro,mi=1e9,si[MN],nm=,num=,be[MN];
long long MMH;
inline void in(int x,int y,int z){b[++num].y=y;b[num].z=z;b[num].ne=l[x];l[x]=num;}
inline int min(int a,int b){return a<b?a:b;}
int dfs(int x,int f){
int S=,s,u=;
for (register int i=l[x];i;i=b[i].ne)
if (b[i].y!=f){
s=dfs(b[i].y,x);
if (u<s) u=s;
S+=s;
MMH+=1LL*b[i].z*min(s,n-s);
}
if (n-S>u) u=n-S;
if (u<mi) ro=x,mi=u;
return S;
}
void DFS(int x,int f,int d){
q[d].push(ma{-x,d});si[d]++;be[x]=d;
for (register int i=l[x];i;i=b[i].ne)
if (b[i].y!=f) DFS(b[i].y,x,d);
}
int work(int u){
while (_q.top().x!=q[_q.top().y].top().x||q[_q.top().y].empty()) _q.pop();
ma o;
if (_q.top().y==u) o=_q.top(),_q.pop();
while (_q.top().x!=q[_q.top().y].top().x||q[_q.top().y].empty()) _q.pop();
u=_q.top().y;
if (o.x) _q.push(o);
return u;
}
int main(){
register int i;
n=read();
if (n==) return puts("0\n1"),;
for (i=;i<n;i++) x=read(),y=read(),z=read(),in(x,y,z),in(y,x,z);
dfs(,);
q[].push(ma{-ro,});_q.push(ma{-ro,});si[]=;
for (i=l[ro];i;i=b[i].ne)
DFS(b[i].y,ro,++nm),Q.push(ma{si[nm]<<,nm}),_q.push(ma(q[nm].top().x,nm));
printf("%lld\n",MMH<<);
for (i=;i<=n;i++){
while (Q.top().x!=si[Q.top().y]+q[Q.top().y].size()) Q.pop();
if (be[i]==Q.top().y||Q.top().x<n-i+) m=work(be[i]);else m=Q.top().y;
if (i==ro&&-q[m].top().x>ro&&!q[].empty()&&Q.top().x<n-i+) m=;
printf("%d ",-q[m].top().x);
q[m].pop();si[be[i]]--;if (!q[m].empty())_q.push(ma(q[m].top().x,m));
Q.push(ma(si[m]+q[m].size(),m));Q.push(ma(si[be[i]]+q[be[i]].size(),be[i]));
}
}