[数据结构]最小生成树

一、有关生成树的几个概念:

连通图:在无向图中,若任意两个顶点都有路径相通,则称该无向图为连通图。

强连通图:在有向图中,若任意两个顶点都有路径相通,则称该有向图为强连通图。

连通网:在连通图中,若图的边具有一定的意义,每一条边都对应着一个数,称为权;权代表着连接连个顶点的代价,称这种连通图叫做连通网。

生成树:一个连通图的生成树是指一个连通子图,它含有图中全部n个顶点,但只有足以构成一棵树的n-1条边。一颗有n个顶点的生成树有且仅有n-1条边,如果生成树中再添加一条边,则必定成环。

最小生成树:在连通网的所有生成树中,所有边的代价和最小的生成树(即权重和最小),称为最小生成树。(最小权重和生成树的简称)

次最小生成树:除了最小生成树外的生成树最小权值和是多少。

特别地,瓶颈生成树:在无向图G中的瓶颈生成树,它的最大边权值是G中所有生成树的最大边权值最小的那个。

无向图的最小生成树一定是瓶颈生成树,但瓶颈生成树不一定是最小生成树。(最小瓶颈生成树==最小生成树)

二、最小生成树实现方法:

1、prim(普里姆)算法:用类似Dijkstra最短路径算法,首先用数组dis来记录生成树(开始只是一个顶点)到各个顶点的距离,也就是说记录现在的最短距离,不是Dijkstra中每个顶点到1号顶点的最短距离,而是每个顶点到任意一个“树顶点”(已被选入生成树的顶点)的最短距离即dis[k]>e[j][k]则更新dis[k]=e[j][k];不需要加dis[j]了,我们的目的并不是非得靠近1号顶点,只需靠近生成树任意一个顶点就可以。

2、Kruskcal(克鲁斯卡尔)算法:通过从小到大排序边权值,结合并查集算法,从最小边开始不断连通顶点找出(除了已经选了的)最小顶点,直到所有顶点连接成生成树,并找到最小权值和。

HDUOJ1233模板题:http://acm.hdu.edu.cn/showproblem.php?pid=1233

1、最小生成树(MST)之Kruskcal

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int f[110];
struct edge{
    int u;
    int v;
    int w;
}e[10010];
bool cmp(const struct edge &a,const struct edge &b){
    return a.w<b.w;
}
int find (int x){
   while(x!=f[x]) x = f[x];
   return x;
}
int merge(int x,int y){
   x = find(x);
   y = find(y);
   if(x!=y){
     f[y] = x;
     return 1;
   }
   return 0;
}
int main(){
    int n;
   while(~scanf("%d",&n)){
        if(n==0) break;
        int m=n*(n-1)/2;
        for(int i=1;i<=n;i++) f[i] = i;
        for(int i=1;i<=m;i++){
            scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
        }
        sort(e+1,e+m+1,cmp);
        int coun = 0;
        int sum = 0;
       for(int i=1;i<=m;i++){
          if(merge(e[i].u,e[i].v)){
            coun++;
            sum+=e[i].w;
          }
          if(coun==n-1) break;
       }
        printf("%d\n",sum);
   }
 return 0;
}

2、最小生成树(MST)之Prim


 

#include<stdio.h>
#include<string.h>
#define inf 0x3f3f3f;
int e[100][100];
bool vis[100];
int dis[100];
int main(){
    int n;
   while(~scanf("%d",&n)){
        if(n==0) break;
        memset(vis,false,sizeof(vis));
        int m=n*(n-1)/2;
        int u,v,w;
        for(int i=0;i<m;i++){
            scanf("%d%d%d",&u,&v,&w);
            e[u][v] = w;
            e[v][u] = w;
        }
        for(int i=1;i<=n;i++){
            dis[i] = e[1][i];
        }
        vis[1] = true;
        int coun = 1;
        int sum = 0;
        int x;
        while(coun<n){
            int minx = inf;
            for(int i=1;i<=n;i++){
                if(!vis[i]&&dis[i]<minx){
                    x=i;
                    minx = dis[i];
                }
            }
            vis[x] = true;
            coun++;
            sum+=dis[x];
            for(int i=1;i<=n;i++)
                if(!vis[i]&&dis[i]>e[x][i])
                  dis[i] = e[x][i];
        }
        printf("%d\n",sum);
   }
 return 0;
}

3、瓶颈生成树


Out of Hay

Description

The cows have run out of hay, a horrible event that must be remedied immediately. Bessie intends to visit the other farms to survey their hay situation. There are N (2 ≤ N ≤ 2,000) farms (numbered 1..N); Bessie starts at Farm 1. She'll traverse some or all of the M (1 ≤ M ≤ 10,000) two-way roads whose length does not exceed 1,000,000,000 that connect the farms. Some farms may be multiply connected with different length roads. All farms are connected one way or another to Farm 1.

Bessie is trying to decide how large a waterskin she will need. She knows that she needs one ounce of water for each unit of length of a road. Since she can get more water at each farm, she's only concerned about the length of the longest road. Of course, she plans her route between farms such that she minimizes the amount of water she must carry.

Help Bessie know the largest amount of water she will ever have to carry: what is the length of longest road she'll have to travel between any two farms, presuming she chooses routes that minimize that number? This means, of course, that she might backtrack over a road in order to minimize the length of the longest road she'll have to traverse.

Input

* Line 1:           Two space-separated integers, N and M.

* Lines 2..1+M:   Line i+1 contains three space-separated integers, AiBi, and Li, describing a road from Ai to Bi of length Li.

Output

* Line 1:   A single integer that is the length of the longest road required to be traversed.

Sample Input

3 3
1 2 23
2 3 1000
1 3 43

Sample Output

43

Hint

OUTPUT DETAILS:

In order to reach farm 2, Bessie travels along a road of length 23. To reach farm 3, Bessie travels along a road of length 43. With capacity 43, she can travel along these roads provided that she refills her tank to maximum capacity before she starts down a road.

此题正是典型的瓶颈生成树。

#include <cstdio>
#include <algorithm>
using namespace std;
struct edge{
    int u;
    int v;
    int w;
    }e[10010];
int f[10010];
bool cmp(const edge &a,const edge &b){
    return a.w<b.w;
}
int getf(int x){
     if(f[x]==x)  return x;
     else return getf(f[x]);
}
int mergex(int u,int v){
       int t1;
       int t2;
       t1=getf(u);
       t2=getf(v);
       if(t1!=t2){
            f[t2]=t1;
            return 1;
       }
       return 0;
}
int main(){
      int n,m;
      while(~scanf("%d%d",&n,&m)){
        for(int i=1;i<=m;i++)
            scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
        sort(e+1,e+1+m,cmp);
        for(int i=1;i<=n;i++)
            f[i]=i;
        int ans=0;
        int sum=0;
        int tnt;
        for(int i=1;i<=m;i++)
        {
            if(mergex(e[i].u,e[i].v))
            {
               ans++;
               sum+=e[i].w;
            }
            if(ans==n-1)
            {
               tnt=e[i].w;
               break;
            }
        }
        printf("%d\n",tnt);
      }
      return 0;
}

4、


Cheering up the Cows

Description

Far

Slim Span

  • Time Limit: 4000/2000 MS (Java/Others)     Memory Limit: 65536/65536 K (Java/Others)
  • Total Submission(s): 162     Accepted Submission(s): 77

Description

Given an undirected weighted graph G, you should find one of spanning trees specified as follows.

The graph G is an ordered pair (VE), where V is a set of vertices {v1v2, …, vn} and E is a set of undirected edges {e1e2, …, em}. Each edge e ∈ E has its weight w(e).

A spanning tree T is a tree (a connected subgraph without cycles) which connects all the n vertices with n-1 edges. The slimness of a spanning tree T is defined as the difference between the largest weight and the smallest weight among the n-1 edges of T.


Figure 1: A graph G and the weights of the edges

For example, a graph G in Figure 1(a) has four vertices {v1v2v3v4} and five undirected edges {e1e2e3e4e5}. The weights of the edges are w(e1) = 3, w(e2) = 5, w(e3) = 6, w(e4) = 6, w(e5) = 7 as shown in Figure 1(b).Figure 2: Examples of the spanning trees of G

There are several spanning trees for G. Four of them are depicted in Figure 2(a)~(d). The spanning tree Ta in Figure 2(a) has three edges whose weights are 3, 6 and 7. The largest weight is 7 and the smallest weight is 3 so that the slimness of the tree Ta is 4. The slimnesses of spanning trees TbTc and Td shown in Figure 2(b), (c) and (d) are 3, 2 and 1, respectively. You can easily see the slimness of any other spanning tree is greater than or equal to 1, thus the spanning tree Td in Figure 2(d) is one of the slimmest spanning trees whose slimness is 1.

Your job is to write a program that computes the smallest slimness.

Input

The input consists of multiple datasets, followed by a line containing two zeros separated by a space. Each dataset has the following format.

nm 
a1b1w1
  
ambmwm

Every input item in a dataset is a non-negative integer. Items in a line are separated by a space. n is the number of the vertices and m the number of the edges. You can assume 2 ≤ n ≤ 100 and 0 ≤ m ≤ n(n - 1)/2. ak and bk (k = 1, …,m) are positive integers less than or equal to n, which represent the two vertices vak and vbk connected by the k-th edge ekwk is a positive integer less than or equal to 10000, which indicates the weight of ek. You can assume that the graph G = (VE) is simple, that is, there are no self-loops (that connect the same vertex) nor parallel edges (that are two or more edges whose both ends are the same two vertices).

Output

For each dataset, if the graph has spanning trees, the smallest slimness among them should be printed. Otherwise, -1 should be printed. An output should not contain extra characters.

Sample Input

4 5
1 2 3
1 3 5
1 4 6
2 4 6
3 4 7
4 6
1 2 10
1 3 100
1 4 90
2 3 20
2 4 80
3 4 40
2 1
1 2 1
3 0
3 1
1 2 1
3 3
1 2 2
2 3 5
1 3 6
5 10
1 2 110
1 3 120
1 4 130
1 5 120
2 3 110
2 4 120
2 5 130
3 4 120
3 5 110
4 5 120
5 10
1 2 9384
1 3 887
1 4 2778
1 5 6916
2 3 7794
2 4 8336
2 5 5387
3 4 493
3 5 6650
4 5 1422
5 8
1 2 1
2 3 100
3 4 100
4 5 100
1 5 50
2 5 50
3 5 50
4 1 150
0 0

Sample Output

1
20
0
-1
-1
1
0
1686
50

Hint

与“最小生成树”有关:求一棵最大边与最小边差值最小的生成树,可利用kruskal

方法一:二分差值

方法二:枚举最小边

 

#include<cstdio>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
struct edge{
   int u,v,w;
   bool operator<(const edge&a)const{
        return w<a.w;
   }
}e[5000];
int f[110];
int n,m;
int getf(int x){
     if(f[x]==x) return x;
     else return getf(f[x]);
}
void make(){for(int i=1;i<=n;i++) f[i]=i;}
int main(){
          while(~scanf("%d%d",&n,&m)){
                if(n==0&&m==0) break;
            for(int i=1;i<=m;i++)
                scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
            sort(e+1,e+1+m);
            int ans,tnt;
            int cnt;
            ans=INF;
            for(int i=1;i<=m;i++){
               make();///每次初始化数组f
                cnt=0,tnt=INF;
                for(int j=i;j<=m;j++){
                    int t1=getf(e[j].u);
                    int t2=getf(e[j].v);
                    if(t1!=t2){
                        f[t2]=t1;
                        ++cnt;
                        if(cnt==n-1){
                            tnt=e[j].w-e[i].w;
                            break;
                        }
                    }
                }
            if(ans>tnt) ans=tnt;///更新每个生成树最大边与最小边差值
            }
            if(ans==INF) puts("-1");
            else printf("%d\n",ans);
          }
}

 

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值