CCF认证201412-4最优灌溉

原文链接

我的个人博客

原题链接

CCF认证201412-4最优灌溉

思路

  这个题目和数据中心、地铁修建两个题目都是最小生成树的考点。
  题目给定了n块麦田的m条边的信息,要求找出能够灌溉整个麦田的最小费用。
  很典型的最小生成树的题目,一点弯弯绕也没用。可见相同的考点再次出现时,会变得越来越隐蔽。

代码

#include <bits/stdc++.h>
using namespace std;

struct Edge{//边的类 
	int v1,v2,cost;
	Edge(int vv1,int vv2,int c):v1(vv1),v2(vv2),cost(c){} 
	bool operator <(const Edge&e) const{
		return cost > e.cost;//根据费用进行排序 
	}
}; 
int n,m,ans=0;
priority_queue <Edge> edges;//用队列存放边,自动排序
int father[100050];
//查找父亲节点 
int findfather(int x){
	//查找根节点,并进行路径压缩
	int son = x,root = x;
	while(root != father[root]){
		root = father[root];//查找根节点 
	}
	//将所有root作为所有孩子节点的直接父亲 
	while(son != root){
		int tmp = father[son];
		father[son] = root;
		son = tmp;
	}
	return root;//返回父亲节点 	 
} 

int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n+10;i++){
		father[i] = i;
	} 
	while(m--){
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		edges.emplace(a,b,c);
	}
	while(!edges.empty()){
		Edge e = edges.top();
		edges.pop();
		int fa = findfather(e.v1);
		int fb = findfather(e.v2);
		if(fa != fb){
			father[fa] = fb;
			ans += e.cost;//更新最长边 
		} 
	}
	printf("%d",ans);
	return 0; 
	
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章