pku2485Highways(kruskal)

Xredman posted @ Mar 23, 2010 01:12:48 AM in Algorithm with tags pku MST kruskal , 1007 阅读

kruskal求MST

6613058 Xredman 2485 Accepted 412K 235MS C++ 1727B 2010-03-23 11:58:24
//6613058 Xredman 2485 Accepted 412K 235MS C++ 1727B 2010-03-23 11:58:24 
/*
Kruskal MST模板:适用于无向图 
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

const int MAX_SIZE = 502;

typedef struct
{
	int parent;
	int height;
}Node;

typedef struct Edge 
{
	int u, v, dist;
	Edge(){};
	Edge(int tu, int tv, int tdist):u(tu),v(tv),dist(tdist){};
	bool operator<(const Edge edge) const
	{
		return dist < edge.dist;
	}
}Edge;

Edge edge[MAX_SIZE * MAX_SIZE];

Node UFSet[MAX_SIZE];

int nEdge;

void make_set(int n)
{//初始化并查集 
	for(int i = 0; i < n; i++)
	{
		UFSet[i].parent = i;
		UFSet[i].height = 1;
	}
} 

int find(int x)
{//O(n) 
	while(x != UFSet[x].parent)
		x = UFSet[x].parent;
	return x;
}

bool merge(int x, int y)
{//O(1)
	x = find(x);
	y = find(y);
	if(x == y)
		return false;
	if(UFSet[x].height == UFSet[y].height)
	{
		UFSet[y].parent = x;
		UFSet[x].height++;
	}else if(UFSet[x].height > UFSet[y].height)
	{
		UFSet[y].parent = x;
	}else
	{
		UFSet[x].parent = y;
	}
}

void readin(int n)
{
	nEdge = 0;
	int i, j;
	for(i = 0; i < n; i++)
	{
		for(j = 0; j < n; j++)
		{
			if(i < j)
			{
				edge[nEdge].u = i;
				edge[nEdge].v = j;
				scanf("%d", &edge[nEdge++].dist);
			}
			else
			{
				scanf("%*d");
			}
		}
	}	
	make_set(n);
}

int kruskal()
{
	int i, maxx = 0;;
	int x, y;
	sort(edge, edge + nEdge);

	for(i = 0; i < nEdge; i++)
	{
		x = find(edge[i].u);
		y = find(edge[i].v);
		if(x != y)
		{
			merge(x, y);
			maxx = edge[i].dist > maxx ? edge[i].dist : maxx;
		}
	}
	return maxx;
}

int main()
{
	int n;
	int T;
	scanf("%d", &T);
	while(T-- && scanf("%d", &n))
	{
		readin(n);
		printf("%d\n",kruskal());
	}
	return 0;
} 

 






CBSE 4th Class Syll 说:
Aug 31, 2023 08:34:11 PM

CBSE 4 Class Syllabus 2024 is Recently Released by Central Board of Secondary Education (CBSE) and National Council of Educational Research and Training (NCERT). It Contains Important information Related to the CBSE Class Course Structure of the Subject. Students are Advised to Thoroughly go Through the CBSE Class Syllabus 2024 before they Start Studying for the new Session. It will CBSE 4th Class Syllabus 2024 be Quite helpful to Structure your Study plan and work in a Productive way.CBSE 4th Class Examination Every Year Conducted Month of February , In this Web page you will get the Complete Syllabus of CBSE Class Mathematics, Chemistry, Physics, Biology, Social Science, Science, Hindi, Science is Available here for Download in Pdf format.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter