Uva 1395 Slim Span

本文介绍了一种使用并查集解决特定图论问题的方法。通过对边进行排序,并逐步加入边来寻找满足条件的最小边权差值,适用于算法竞赛及图论问题求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比较基础的一道题目,将边排序之后利用并查集查找以每一条边为起点是否存在更短的满足题意的差值,如果存在那么进行更新即可,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;

class Edge{
public:
	int left, right, weight;
};

bool compare(const Edge& a,const Edge& b){
	return a.weight < b.weight;
}

Edge edge[5005];

int root[5005];
const int Inf = 0x3f3f3f3f;

class Solve{
public:
	int n, m;
	int amount;
	void Init(){
		for (int i = 0; i < m; i++){
			cin >> edge[i].left >> edge[i].right >> edge[i].weight;
		}
		sort(edge,edge+m,compare);
	}

	void initRoot(){//点的坐标是从1开始的
		for (int i = 1; i <= m; i++)
			root[i] = i;
	}

	int findRoot(int a){
		int r = a;
		while (r != root[r]){
			r = root[r];
		}
		int t;
		while (root[a] != r){
			t = root[a];
			root[a] = r;
			a = t;
		}
		return r;
	}

	void Union(int a,int b){
		int root_a = findRoot(a);
		int root_b = findRoot(b);
		if (root_a != root_b){
			amount--;
			root[root_a] = root_b;
		}
	}

	void Deal(){
		Init();
		int ans = Inf;
		for (int i = 0; i < m; i++){
			initRoot();
			amount = n - 1;
			for (int j = i; j < m; j++){
				Union(edge[j].left, edge[j].right);
				if (amount == 0){
					ans = min(ans,edge[j].weight-edge[i].weight);
				}
			}
		}
		if (ans == Inf) cout << "-1" << endl;
		else cout << ans << endl;
	}
};

int main(){
	Solve a;
	while (cin >> a.n >> a.m){
		if (a.n == 0 && a.m == 0) break;
		a.Deal();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值