您的位置:首页 > 其它

Uva 1395 Slim Span

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

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: