HDU 1233 (最小生成樹) 用並查集實現kruskal

題目很簡單,不過有些細節要注意

#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000

struct edge1
{
	int x,y;
	int weigh;
}edge[MAX];

int father[MAX];


bool cmp(edge1 a, edge1 b)  
{  
	return a.weigh < b.weigh;  
}  



void init(int n)
{
	for(int i=0;i<=n;i++)       //這裏要注意,如果寫成i<n,那麼就會WA,原因是第N個數沒有開闢出節點,看清題意,他是從1...N,我錯了半天才找出來
	{
		father[i]=i;
	}
}

int find_set(int x)
{
	if(x==father[x]) return x;
	father[x]=find_set(father[x]);
	return father[x];
}



void union_set(int x,int y)
{
	father[y]=x;
}



void main()
{
	int N,i,a,b, sum,M;
	while(cin>>N)
	{
		if(N==0) break;
		init(N);
		 sum=0;
		 M=N*(N-1)/2;
		for(i=0;i<M;i++)
		{
			cin>>edge[i].x>>edge[i].y>>edge[i].weigh;

		}

		sort(edge,edge+M,cmp);


		for(i=0;i<M;i++)
		{
			a=find_set(edge[i].x);
			b=find_set(edge[i].y);
			if(a!=b)
			{
				union_set(a,b);
				sum+=edge[i].weigh;
			}
		}
		cout<<sum<<endl;
	}
}


 

這樣寫可能有些彆扭,我們乾脆把數組從下標“1”開始存儲

#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000

struct edge1
{
	int x,y;
	int weigh;
}edge[MAX];

int father[MAX];


bool cmp(edge1 a, edge1 b)  
{  
	return a.weigh < b.weigh;  
}  



void init(int n)
{
	for(int i=1;i<=n;i++)
	{
		father[i]=i;
	}
}

int find_set(int x)
{
	if(x==father[x]) return x;
	father[x]=find_set(father[x]);
	return father[x];
}



void union_set(int x,int y)
{
	father[y]=x;
}



void main()
{
	int N,i,a,b, sum,M;
	while(cin>>N)
	{
		if(N==0) break;
		init(N);
		 sum=0;
		 M=N*(N-1)/2;
		for(i=1;i<=M;i++)
		{
			cin>>edge[i].x>>edge[i].y>>edge[i].weigh;

		}

		sort(edge+1,edge+1+M,cmp);


		for(i=1;i<=M;i++)
		{
			a=find_set(edge[i].x);
			b=find_set(edge[i].y);
			if(a!=b)
			{
				union_set(a,b);
				sum+=edge[i].weigh;
			}
		}
		cout<<sum<<endl;
	}
}


下面附上用冒泡法寫的算法,不過沒有AC過,超時間

#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000

struct edge1
{
	int x,y;
	int weigh;
}edge[MAX];

int father[MAX];


bool cmp(edge1 a, edge1 b)  
{  
	return a.weigh < b.weigh;  
}  



void init(int n)
{
	for(int i=1;i<=n;i++)
	{
		father[i]=i;
	}
}

int find_set(int x)
{
	if(x==father[x]) return x;
	father[x]=find_set(father[x]);
	return father[x];
}



void union_set(int x,int y)
{
	father[y]=x;
}



void main()
{
	int N,i,a,b, sum,M;
	while(cin>>N)
	{
		if(N==0) break;
		init(N);
		 sum=0;
		 M=N*(N-1)/2;
		for(i=1;i<=M;i++)
		{
			cin>>edge[i].x>>edge[i].y>>edge[i].weigh;

		}

		sort(edge+1,edge+1+M,cmp);


		for(i=1;i<=M;i++)
		{
			a=find_set(edge[i].x);
			b=find_set(edge[i].y);
			if(a!=b)
			{
				union_set(a,b);
				sum+=edge[i].weigh;
			}
		}
		cout<<sum<<endl;
	}
}


 

發佈了35 篇原創文章 · 獲贊 42 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章