题意:求最一个生成树 , 使得这个生成树中最大权值边减去最小权值边的值最小。
解法:我们可以枚举所有生成树 , 但是这样时间消耗太大 。 因此 , 我们可以考虑到 , 在这些生成树中有一些生成树是没有必要枚举的 。 我们要求的这个值只跟生成树中的最小权值和最大权值有关联 , 因此我们只需要枚举生成树中的最小值和最大值 , 又对于一个确定最小值的生成树中 , 最大权值的最小值 , 就是确定最小值得最小生成树 , 因此我们就只需要枚举最小边了。
还有另外一种解法就是:二分我们要求的这个值 , 其实这种方法的本质思想和前面的思想一样 , 并且还浪费更多的时间
这里只给出前面的代码
代码:
//要判断这个图是不是连通图 kruskal算法
#include
#include
#include
#include
using namespace std;
#define maxn 110
struct node
{
int x , y;
int w;
}edge[maxn*maxn];
int n , m , p[maxn];
bool cmp(const node x , const node y)
{
return x.w <= y.w;
}
int find(int x)
{
int g= x , h;
while(x != p[x])
x = p[x];
while(g != x)
{
h = p[g];
p[g] = x;
g = h;
}
return x;
}
int kruskal(int xy)
{
//sort() 对边进行排序
int i ;
for(i = 1; i <= n; i++)
p[i] = i;
int k = 0 , x , y;
for(i = xy; i < m ; i++)
{
x = find(edge[i].x);
y = find(edge[i].y);
if(x != y)
p[x] = p[y] , k += 1;
if(k == n-1)
break;
}
return edge[i].w-edge[xy].w;
}
int main()
{
while(scanf("%d %d" , &n , &m) && (n+m))
{
int i ;
if(m == 0)
{
cout<<"-1"<<endl;
continue;
}
for(i = 0; i < m; i++)
scanf("%d %d %d" , &edge[i].x , &edge[i].y , &edge[i].w);
for(i = 1; i <= n; i++)
p[i] = i;
sort(edge , edge+m , cmp);
//cout<<i<<endl;
int k = 0 , x , y;
for(i = m-1; i >=0 ; i--)
//确定给出的图是不是连通图 , 并且确定从最大权值开始 , 要组成一个连通图 , 最少需要多少边
{
x = find(edge[i].x);
y = find(edge[i].y);
if(x != y)
p[x] = y , k += 1;
if(k == n-1)
break;
}
if(k != n-1)
{
cout<<"-1"<<endl;
continue;
}
k = i;
int min_shu = 100000;
for(i = 0; i <= k; i++) //枚举最小边
{
if(edge[i+n-2].w-edge[i].w > min_shu)
continue;
x = kruskal(i);
if(min_shu > x)
min_shu = x;
}
cout<<min_shu<<endl;
}
return 0;
}
解法:我们可以枚举所有生成树 , 但是这样时间消耗太大 。 因此 , 我们可以考虑到 , 在这些生成树中有一些生成树是没有必要枚举的 。 我们要求的这个值只跟生成树中的最小权值和最大权值有关联 , 因此我们只需要枚举生成树中的最小值和最大值 , 又对于一个确定最小值的生成树中 , 最大权值的最小值 , 就是确定最小值得最小生成树 , 因此我们就只需要枚举最小边了。
还有另外一种解法就是:二分我们要求的这个值 , 其实这种方法的本质思想和前面的思想一样 , 并且还浪费更多的时间
这里只给出前面的代码
代码:
//要判断这个图是不是连通图
#include
#include
#include
#include
using namespace std;
#define maxn 110
struct node
{
}edge[maxn*maxn];
int n , m , p[maxn];
bool cmp(const node x , const node y)
{
}
int find(int x)
{
}
int kruskal(int xy)
{
}
int main()
{
}