zoukankan      html  css  js  c++  java
  • 【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
    ",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;
    }
    
  • 相关阅读:
    js组件常用封装方法。。。。。【组件封装】 ★★★★★★ 1月会员日 集人气【弹窗】
    以后开公司用的资源瞎记录
    SpringSecurityFilter 链
    分布式系统数据一致性的6种方案(转)
    统一日志监控系统 springboot websocket 作品
    MyBatis generator 使用方式 小结
    swagger and restful api 参考
    kafka linux 启动脚本 sample
    转 CAS实现SSO单点登录原理
    江南白衣 Java性能优化PPT
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/11217263.html
Copyright © 2011-2022 走看看