poj3522求一棵生成树使最大的边和最小的边差值最小

/*题目:给出一张图,求一棵生成树使得最大边权和最小边权差值最小*/
/*思路:对边权排序,依次枚举最小边,再与后边组成生成树,直到满足题意。若不连通,输出-1,反之,输出差值*/

#include 
#include 
#define N 100

using namespace std;

const int inf = 0x3f3f3f3f;

typedef struct note {
	int u; int v; int w;
}edge;

int n, m;
edge e[N*N];
int f[N];

int cmp(edge a, edge b)
{
	return a.w < b.w;
}

void init()
{
	for (int i = 1; i <= n; i++)
		f[i] = i;
}

int find(int x)
{
	return x == f[x] ? x : f[x] = find(f[x]);
}

int merge(int x, int y)
{
	int t1, t2;
	t1 = find(x); t2 = find(y);
	if (t1 != t2) { f[t2] = f[t1]; return 1; }
	return 0;
	
}

int main()
{
	while (scanf("%d%d", &n, &m) != EOF && (n || m))
	{
		int ans = inf;
		for (int i = 0; i < m; i++)
			scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w);
		sort(e, e + m, cmp);
		for (int i = 0; i < m; i++)
		{
			int cnt = 0;
			init();
			for (int j = i; j < m; j++)
			{
				if (merge(e[j].u, e[j].v))
					cnt++;
				if (cnt == n - 1)
				{
					ans = min(ans, e[j].w - e[i].w);
					break;
				}
			}
		}
		if (ans == inf)	ans = -1;
		printf("%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(最小生成树)