洛谷3931 [洛谷八连测] 一道难题

题目链接

题目:
一棵有根树,每条边上具有割掉该边的代价,求割开这个树的最小代价(所谓割开一棵有根树,就是删除若干条边,使得任何任何叶子节点和根节点不连通) 
DFS入门题,自下而上累计答案求min
//Luogu3931
#include<bits/stdc++.h>
#define MAXN 100007
#define INF 0x7f7f7f7f
using namespace std;
int read(){
    int x=0,t=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')t=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*t;
}
int N,root,cnt,last[MAXN],f[MAXN],p[MAXN];
struct Edge{
    int other,pre,val;
}a[MAXN*2];
void connect(int x,int y,int z){
    a[++cnt]=(Edge){y,last[x],z};
    last[x]=cnt;
}
void DFS(int x)
{
    for(int i=last[x];i;i=a[i].pre){
        int to=a[i].other;
        if(p[x]!=to){
            p[to]=x;
            DFS(to);
            f[x]+=min(f[to],a[i].val);  //割边 还是 继承 取 min
        }
    } 
    if(!f[x])f[x]=INF;            //叶子设正无穷
}
int main()
{
    N=read(),root=read();
    for(int i=1;i<=N-1;i++){
        int x=read(),y=read(),z=read();
        connect(x,y,z);connect(y,x,z);
    }
    DFS(root);
    printf("%d\n",f[root]);
    return 0;
} 

 

转载于:https://www.cnblogs.com/Elfish/p/7642130.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值