【The 13th Chinese Northeast Collegiate Programming Contest E题】

题目大意:给定一棵 N 个点的树,边有边权,定义“线树”为一个图,其中图的顶点是原树中的边,原树中两条有公共端点的边对应在线图中存在一条边,边权为树中两条边的边权和,求线图的最小生成树的代价是多少。

题解:
对于树中的一个顶点来说,假设有 M 条边以该顶点为一个端点,那么这 M 条边对应到线图中的顶点必须要求能够构成一个联通块。另外,可以发现这个问题的解决和其他顶点无关,即:对于树上每个顶点来说,构成了一个子问题。因此,考虑一个贪心策略,即:每次用边权最小的那条边和其他所有边相连,这样的代价是最小的。可以发现每条边仅被考虑两次(两个端点各考虑一次),因此总复杂度为 \(O(M)\)

代码如下

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=1e5+10;
typedef long long LL;
 
int n;LL ans;
struct node{
    int nxt,to;LL w;
}e[maxn<<1];
int tot=1,head[maxn];
inline void add_edge(int from,int to,int w){
    e[++tot]=node{head[from],to,w},head[from]=tot;
}
 
void dfs(int u,int fa,LL fe){
    LL mi=0x3f3f3f3f,cnt=0,ret=0;
    if(fe!=-1)mi=min(mi,fe),ret=fe,cnt=1;
    for(int i=head[u];i;i=e[i].nxt){
        int v=e[i].to;LL w=e[i].w;
        if(v==fa)continue;
        ret+=w,mi=min(mi,w),++cnt;
        dfs(v,u,w);
    }
    LL res=ret+(cnt-2)*mi;
    ans+=res;
}
void read_and_parse(){
    scanf("%d",&n);
    for(int i=1,x,y,z;i<n;i++){
        scanf("%d%d%d",&x,&y,&z);
        add_edge(x,y,z),add_edge(y,x,z);
    }
}
void solve(){
    dfs(1,0,-1);
    printf("%lld\n",ans);
}
void init(){
    tot=1,ans=0;
    for(int i=1;i<=n;i++)head[i]=0;
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        init();
        read_and_parse();
        solve();
    }
    return 0;
}

转载于:https://www.cnblogs.com/wzj-xhjbk/p/11217263.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值