【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;
}
posted @ 2019-07-20 12:02  shellpicker  阅读(212)  评论(0编辑  收藏  举报