zoj 1406 poj 1251 Jungle Roads

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>

using namespace std;

const int MAXN = 27;
const int MAXM = 100;

struct Edge
{
	int u, v, w;
};

Edge edges[MAXM];
int parent[MAXN];
int kcount[MAXN];
int Maxweight;
int n, m;

void UFset()
{
	int i;
	for (i = 0; i < n; ++i)
	{
		parent[i] = i;
		kcount[i] = 1;
	}
}

int Find_Parent( int x )
{
	int s;
	for(s = x; s != parent[s]; s = parent[s])
		;
	while (s != x)
	{
		int tmp = parent[x];
		parent[x] = s;
		x = tmp;
	}
	return s;
}

void Union(int u, int v)
{
	int r1 = Find_Parent( u );
	int r2 = Find_Parent( v );
	if(kcount[r1] > kcount[r2])
	{
		parent[r2] = r1;
		kcount[r1] += kcount[r2];
	}
	else
	{
		parent[r1] = r2;
		kcount[r2] += kcount[r1];
	}
}

void Kruskal()
{
	int i;
	UFset();
	int num  = 0;
	int u, v;
	for (i = 0; i < m; ++i)
	{
		u = edges[i].u;
		v = edges[i].v;
		if(Find_Parent(u) != Find_Parent(v))
		{
			Maxweight += edges[i].w;
			num++;
			Union(u, v);
		}
		if(num >= n-1)
			return;
	}
}

int cmp (const void* a, const void* b)
{
	Edge* aa = ( Edge* )a;
	Edge* bb = ( Edge* )b;
	if(aa->w > bb->w)
		return 1;
	else
		return -1;
}

int main()
{
	char ch;
	int i, j, k;
	int u, v, w;
	while (cin>>n)
	{
		if(n == 0)
			break;
		memset(parent, 0, sizeof(parent));
		int EdgeNum = 0;//严重错误!忘了在这里初始化,注意细节!!!
		for (i = 0; i < n-1; ++i)
		{
			cin>>ch>>k;
			u = ch - 'A';
			for (j = 0; j < k; ++j)
			{
				cin>>ch>>w;
				v = ch - 'A';
				edges[ EdgeNum ].u = u;
				edges[ EdgeNum ].v = v;
				edges[ EdgeNum++ ].w = w;
			}
		}

		m = EdgeNum;

		qsort(edges, m, sizeof(edges[0]), cmp);
		Maxweight = 0;
		Kruskal();

		cout<<Maxweight<<endl;
	}
	return 0;
}

你可能感兴趣的:(MST)