1. 程式人生 > >poj1258 kruskal演算法+並查集 只要47MS我也是醉了

poj1258 kruskal演算法+並查集 只要47MS我也是醉了

//poj1258  kruskal演算法+並查集 為什麼只要47MS? 
#include <iostream>
#include <algorithm>
#define inf 100005
using namespace std;
int max1;
int father[105];
int rank[105];
struct edge{
	int st;
	int ed;
	int w;
}e[10005];
int top = 0;
void addEdge(int x, int y, int z)
{
	e[top].st = x;
	e[top].ed = y;
	e[top].w = z;
	top++;
}
void makeset(int n)
{
	for(int i = 0; i < n; i++)
	{
		father[i] = i;
		rank[i] = 0;
	}
}
int find(int x)
{
	if(x != father[x])
		father[x] = find(father[x]);
	return father[x];
}
bool Union(int x, int y)
{
	int px = find(x);
	int py = find(y);
	if(px != py)
	{
		if(rank[px] > rank[py])
			father[py] = px;
		else
		{
			if(rank[px] == rank[py])
				rank[py]++;
			father[px] = py;
		}
		return true;
	}
	return false;
}
int cmp(const void* a, const void* b)
{
	return ((edge*)a)->w - ((edge*)b)->w;
}
int kruskal(int n)
{
	//排序
	qsort(e, top, sizeof(e[0]), cmp);
 	for(int i = 0; i < top; i++)
 	{
 		if(Union(e[i].st, e[i].ed))
	 	{
				max1 += e[i].w;  	
	 	}
 	}
	return max1;
}
int main()
{
	int n; 
	cin>>n;
	while(n && !cin.eof())
	{
		top = 0;
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < n; j++)
			{
				int w;
				cin>>w;
				addEdge(i, j, w);
			}
		}
		makeset(n);
	 	max1 = 0;
	 	cout<<kruskal(n)<<endl;
	 	cin>>n;
	}
	return 0;	
}