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; 
	
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章