ABC369G 题解
Sol
观察样例发现先选叶子节点把所有的边都用上之后再怎么选答案都不会变,所以一定是先把叶子选完。
考虑贪心地选叶子,一个叶子对答案的贡献是两倍的其到根节点的边权之和,选了这个叶子就把这些边的边权清空。
考虑到一个点管辖的叶子节点是一段连续的区间,我们可以方便地用线段树维护每个叶子的贡献。
因为每条边只会被贡献一次,所以复杂度是 \(O(n\log n)\) 的。
Code
#include <bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int,int> pii;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
const int N=2e5+10,INF=0x3f3f3f3f3f3f3f3f,mod=1e9+7;
int n;
struct edge{
int v,w,nxt;
}e[N*2];
int head[N],cnt=2;
void add(int u,int v,int w){
e[cnt].v=v;
e[cnt].w=w;
e[cnt].nxt=head[u];
head[u]=cnt++;
}
int fa[N],faw[N],L[N],R[N],d[N],rnk[N],num;
void dfs(int u,int f){
L[u]=INF,R[u]=0;
bool lf=1;
for(int i=head[u];i;i=e[i].nxt){
if(e[i].v!=f){
lf=0;
fa[e[i].v]=u,faw[e[i].v]=e[i].w;
d[e[i].v]=d[u]+e[i].w;
dfs(e[i].v,u);
L[u]=min(L[u],L[e[i].v]);
R[u]=max(R[u],R[e[i].v]);
}
}
if(lf)L[u]=R[u]=++num,rnk[num]=u;
}
struct node{
int val,lazy,id;
}t[N*4];
node operator+(node x,node y){
node res=x.val>y.val?x:y;
res.lazy=0;
return res;
}
void pushdown(int p){
t[p*2].val+=t[p].lazy;
t[p*2].lazy+=t[p].lazy;
t[p*2+1].val+=t[p].lazy;
t[p*2+1].lazy+=t[p].lazy;
t[p].lazy=0;
}
void build(int p,int l,int r){
if(l==r){
t[p].val=d[rnk[l]]*2;
t[p].id=l;
return;
}
int m=(l+r)>>1;
build(p*2,l,m);
build(p*2+1,m+1,r);
t[p]=t[p*2]+t[p*2+1];
}
void update(int p,int l,int r,int L,int R,int val){
if(L<=l&&r<=R){
t[p].val+=val;
t[p].lazy+=val;
return;
}
int m=(l+r)>>1;
pushdown(p);
if(L<=m)update(p*2,l,m,L,R,val);
if(R>m)update(p*2+1,m+1,r,L,R,val);
t[p]=t[p*2]+t[p*2+1];
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n;
for(int i=1;i<n;i++){
int u,v,w;
cin>>u>>v>>w;
add(u,v,w),add(v,u,w);
}
dfs(1,0);
build(1,1,num);
int ans=0;
for(int i=1;i<=num;i++){
ans+=t[1].val;
int p=rnk[t[1].id];
while(fa[p]&&faw[p]){
update(1,1,num,L[p],R[p],-2*faw[p]);
faw[p]=0;
p=fa[p];
}
cout<<ans<<'\n';
}
for(int i=num+1;i<=n;i++)cout<<ans<<'\n';
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效