POJ-2377 최소 스패닝 트리 템플릿 (분리 된 세트)

크루스 칼 () 스패닝 트리 템플릿 :

//改进一下,适合一最小最大生成树
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX_E=20100;//注意范围一定要开大
struct edge{
	int u,v;
	long long cost;
}es[MAX_E];
int n,m;//int V,E;//对应顶点数目和边数目
int tree; 
int par[MAX_E],rank[MAX_E];
bool  cmp(const edge& e1,const edge& e2){
	return e1.cost<e2.cost;
}
void init(int n){
	for(int i=0;i<n;i++){
		par[i]=i;
		rank[i]=0;
	}
}
int find(int x){
	if(par[x]==x)
		return x;
	else 
		return par[x]=find(par[x]);
}
void unite(int x,int y){
	x=find(x);
	y=find(y);
	if(x==y)
		return ;
	if(rank[x]<rank[y]){
		par[x]=y;
	}
	else{
		par[y]=x;
		if(rank[x]==rank[y])
			rank[x]++;
	}
}
bool same(int x,int y){
	return find(x)==find(y);
}
long long  Kruskal(){
	sort(es,es+m,cmp);
	init(n);
	tree=n;
	long long res=0;
	for(int i=0;i<m;i++){
		edge e=es[i];
		if(!same(e.u,e.v)){
			unite(e.u,e.v);
			res+=e.cost;
			tree--;//tree用于判断森林是否可以构成树
//if(tree>=2)//cout<<"can not "<<endl;
//else cout<<ans<<endl;
		}
	}
	return res;
}

해당합니다 제목 : POJ2377;

사고 : 부정 ES [I] = .cost -es [I] .cost;

참고 : 할 일이없는 런타임 오류, 크루스 칼은 () 오래 오래 형식을 반환

홈페이지는 다음과 같습니다 :

int main(){
	cin>>n>>m;//顶点数目和边数目 
	for(int i=0;i<m;i++){
		cin>>es[i].u>>es[i].v>>es[i].cost;
		es[i].cost=-es[i].cost;
	}
	long long ans=-Kruskal();
	if(tree>1)
		cout<<"-1"<<endl;
	else
		cout<<ans<<endl;
	
} 
/*Sample Input//求最大路径长度之和,可以考虑转化 
5 8
1 2 3
1 3 7
2 3 10
2 4 4
2 5 8
3 4 6
3 5 2
4 5 17
Sample Output
42
Hint
OUTPUT DETAILS:

The most expensive tree has cost 17 + 8 + 10 + 7 = 42. It uses the following connections: 4 to 5, 2 to 5, 2 to 3, and 1 to 3.*/

 

게시 74 개 원래 기사 · 원의 찬양 (27) · 전망 1796

추천

출처blog.csdn.net/queque_heiya/article/details/103933360