A - Jungle Roads POJ - 1251-水题

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#pragma warning(disable:4996)
using namespace std;
const int maxn = 1005;
int k, m, n,E;
int par[3 * maxn];
int rak[3 * maxn];
int X[maxn];
int Y[maxn];
int D[maxn];
struct edge {
	int  cost;
	int u, v;
};
edge es[1005];
bool cmp(const edge &e1, const edge &e2)
{
	return e1.cost < e2.cost;
}
void init(int n)
{
	for (int i = 0; i < n; i++)
	{
		par[i] = i;
		rak[i] = 0;
	}
}
int find(int x)
{
	if (x == par[x])
		return x;
	else
		return par[x] = find(par[x]);
}
void unite(int x, int y)
{
	x = find(x);
	y = find(y);
	if (x == y)
		return;
	if (rak[x] < rak[y])
		par[x] = y;
	else
	{
		par[y] = x;
		if (rak[x] == rak[y])rak[x]++;
	}
}
bool same(int x, int y)
{
	return find(x) == find(y);
}
int krustal(int E)
{
	sort(es, es + E, cmp);
	init(n);
	int res = 0;
	for (int i = 0; i < E; i++)
	{
		edge e = es[i];
		if (!same(e.u, e.v))
		{
			unite(e.u, e.v);
			res += e.cost;
		}
	}
	return res;
}
int main()
{
	while (scanf("%d",&n)!=EOF&&n!=0)
	{
		int E = 0;
		for (int i = 0; i < n - 1; i++)
		{
			int x;
			char ch;
			cin >> ch >> x;
			for (int j = 0; j < x; j++)
			{
				char t;
				es[E].u = ch-'A';
				cin>>t>>es[E].cost;
				es[E].v = t - 'A';
				E++;
			}
		}
		int sum = krustal(E);
		printf("%d\n",sum);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_17175221/article/details/80588150
今日推荐