poj2485 Kruskal算法+并查集 922MS险过

//poj 2485 kruskal算法+并查集 TLE 922MS擦线(1000MS)过 
#include <iostream>
#include <algorithm>
#define inf 65537
using namespace std;
int max1;
int father[501];
int rank[501];
struct edge{
	int st;
	int ed;
	int w;
}e[125255];
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))
	 	{
			if(e[i].w > max1)
				max1 = e[i].w;  	
	 	}
 	}
	return max1;
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		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;
	}
	return 0;	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值