题目:题目链接
题意:题目的意思就是给你n个点和m条边,然后构造一个生成树,使得在这颗生成树里面权值最大的和权值最小的差值最小;
分析:并查集,直接对边进行一次排序,按照权值由小到大,一次枚举一条边,求一次生成树,寻求过程中,是每次
将一个边加入图中,判断图是否连通判断过程用并查集,一直更新最小值就可以了(练习写了一下最小生成树,略慢):
#include <iostream>
#include <cstdio>
#include <string>
#include <string.h>
#include <map>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <stack>
#include <functional>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cassert>
#include <bitset>
#include <stack>
#include <ctime>
#include <list>
#define INF 0x7fffffff
#define max3(a,b,c) (max(a,b)>c?max(a,b):c)
#define min3(a,b,c) (min(a,b)<c?min(a,b):c)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
#define maxn 105
const int maxm = maxn*maxn/2;
struct Edge
{
int a, b, w;
} edge[maxm];
int n, m;
int father[maxn];
bool operator < (const Edge &a, const Edge &b)
{
return a.w < b.w;
}
void input()
{
for(int i = 0; i < m; ++i)
{
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
a--;
b--;
edge[i].a = a;
edge[i].b = b;
edge[i].w = w;
}
}
int getanc(int a)
{
if(a == father[a])
return a;
return father[a] = getanc(father[a]);
}
int cal(int l)
{
for(int i = 0; i < n; ++i)
father[i] = i;
int i = l;
int block_num = n;
while(i < m && block_num > 1)
{
int a = getanc(edge[i].a);
int b = getanc(edge[i].b);
if(a != b)
{
block_num--;
father[a] = b;
}
i++;
}
if(block_num > 1)
return -1;
return edge[i-1].w - edge[l].w;
}
void work()
{
int ans = cal(0);
if(ans == -1)
{
printf("-1\n");
return;
}
for(int i = 1; i < m; ++i)
{
if(edge[i].w == edge[i-1].w)
continue;
int temp = cal(i);
if(temp == -1)
break;
ans = min(ans, temp);
}
printf("%d\n", ans);
}
int main()
{
while(scanf("%d%d", &n, &m), n|m)
{
mem(edge, 0);
input();
sort(edge, edge+m);
work();
}
}