最小生成树

167 阅读2分钟

最小生成树

  • 最小生成树问题对应的图一般都是无向图

Snipaste_2023-03-16_19-43-53.png

朴素prim

  • 时间复杂度是 O(n^2^+m),n表示点数,m表示边数
  • 适用于稠密图

Snipaste_2023-03-16_19-43-23.png

  • C++
int n;      // n表示点数
int g[N][N];        // 邻接矩阵,存储所有边
int dist[N];        // 存储其他点到当前最小生成树的距离
bool st[N];     // 存储每个点是否已经在生成树中


// 如果图不连通,则返回INF(值是0x3f3f3f3f), 否则返回最小生成树的树边权重之和
int prim()
{
    memset(dist, 0x3f, sizeof dist);

    int res = 0;
    //循环n次,每次加入一个点,一共n个点
    for (int i = 0; i < n; i ++ )
    {
        int t = -1;
        for (int j = 1; j <= n; j ++ )
            //选择不在最小生成树点集内但是距离其最近的点
            if (!st[j] && (t == -1 || dist[t] > dist[j]))
                t = j;

        if (i && dist[t] == INF) return INF;

        if (i) res += dist[t];
        st[t] = true;

        for (int j = 1; j <= n; j ++ ) dist[j] = min(dist[j], g[t][j]);
    }

    return res;
}
  • Java
public static int[][] g = new int[N][N];     //邻接矩阵,存储所有边
public static int[] dist = new int[N];       //存储所有点到当前最小生成树的距离
public static boolean[] st = new boolean[N]; //存储每个点是否已经在最小生成树中

public static int prim() {
    //初始化
    Arrays.fill(dist, 0x3f3f3f3f);
    int res = 0;
    
    //循环n次,每次加入一个点,一共n个点
    for (int i = 0; i < n; i ++) {
        int t = -1;
        //选择不在最小生成树点集内但是距离其最近的点
        if (!st[t] && (t == -1 || dist[t] > dist[j])) {
            t = j;
        }
    }
    st[t] = true;
    
    //只有第一次加入的点距离是0x3f3f3f3f,如果不是第一次加入并且距离是0x3f3f3f3f,说明不是连通图
    if (i != 0 && dist[t] == 0x3f3f3f3f) {
        return 0x3f3f3f3f;
    }
    
    //如果不是第一个添加的点
    if (i != 0) {
        res += dist[t];
    }
    //先将dist[t]加进res中再更新,防止出现自环
    //更新其他点到最小生成树点集的最小距离
    for (int j = 1; j <= n; j++) {
        dist[j] = Math.min(dist[j], g[t][j]);
    }
    
    return res;
}

堆优化版prim

  • 时间复杂度O(mlogn)
  • 优化方式和用堆优化dijkstra一样
  • 不如Kruskal

Snipaste_2023-03-16_20-52-03.png

Kruskal

  • 时间复杂度是 O(mlogm), n表示点数,m 表示边数
  • 适用于稀疏图

Snipaste_2023-03-16_22-54-32.png

  • C++
int n, m;       // n是点数,m是边数
int p[N];       // 并查集的父节点数组

struct Edge     // 存储边
{
    int a, b, w;

    bool operator< (const Edge &W)const
    {
        return w < W.w;
    }
}edges[M];

int find(int x)     // 并查集核心操作
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int kruskal()
{
    sort(edges, edges + m);

    for (int i = 1; i <= n; i ++ ) p[i] = i;    // 初始化并查集

    int res = 0, cnt = 0;
    for (int i = 0; i < m; i ++ )
    {
        int a = edges[i].a, b = edges[i].b, w = edges[i].w;

        a = find(a), b = find(b);
        if (a != b)     // 如果两个连通块不连通,则将这两个连通块合并
        {
            p[a] = b;
            res += w;
            cnt ++ ;
        }
    }

    if (cnt < n - 1) return INF;
    return res;
}
  • Java
public static int[] p = new int[N];  //并查集的父节点数组
public static Edge[] edges = new Edge[M];  //存储边

public static class Edge implements Comparable<Pair> {
    public int a;
    public int b;
    public int w;

    public Pair(int a, int b, int w) {
        this.a = a;
        this.b = b;
        this.w = w;
    }

    @Override
    public int compareTo(Pair o) {
        return this.w - o.w;
    }
}

//并查集核心操作
public static int find(int x) {
    if (p[x] != x) {
        p[x] = find(p[x]);
    }
    return p[x];
}

//返回最小生成树的权重和
public static int kruskal() {
    Arrays.sort(edges);
    
    //初始化并查集
    for (int i = 1; i <= n; i++) {
        p[i] = i;
    }
    
    int res = 0;  //存最小生成树的权重和
    int cnt = 0;  //存当前的最小生成树内有几个点
    for (int i = 0; i < m; i++) {
        int a = edges[i].a;
        int b = edges[i].b;
        int w = edges[i].w;
        
        a = find(a);
        b = find(b);
        //如果两个连通块不连通,则将这两个连通块合并
        if (a != b) {
            p[a] = b;
            res += w;
            cnt++;
        }
    }
    
    if (cnt < n - 1) {
        return 0x3f3f3f3f;
    }
    return res;
}

练习

01 Prim算法求最小生成树

  • 题目

Snipaste_2023-03-16_20-39-48.png

  • 题解
import java.io.*;
import java.util.*;

public class Main {
    public static final int N = 510;
    public static int[][] g = new int[N][N];  //邻接矩阵,存储所有边
    public static int[] dist = new int[N];  //存储所有点到当前最小生成树的距离
    public static boolean[] st = new boolean[N];  //存储每个点是否已经在最小生成树中
    public static int n, m;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
        String[] str1 = br.readLine().split(" ");
        n = Integer.parseInt(str1[0]);
        m = Integer.parseInt(str1[1]);
        for (int i = 0; i < N; i++) {
            Arrays.fill(g[i], 0x3f3f3f3f);
        }

        while (m-- > 0) {
            String[] str2 = br.readLine().split(" ");
            int a = Integer.parseInt(str2[0]);
            int b = Integer.parseInt(str2[1]);
            int c = Integer.parseInt(str2[2]);
            g[a][b] = g[b][a] = Math.min(g[a][b], c);
        }

        int t = prim();

        if (t == 0x3f3f3f3f) {
            pw.println("impossible");
        } else {
            pw.println(t);
        }
        br.close();
        pw.close();
    }

    public static int prim() {
        //初始化
        Arrays.fill(dist, 0x3f3f3f3f);
        int res = 0;

        //循环n次,每次加入一个点,一共n个点
        for (int i = 0; i < n; i++) {
            int t = -1;
            //选择不在最小生成树点集内但是距离其最近的点
            for (int j = 1; j <= n; j++) {
                if (!st[j] && (t == -1 || dist[t] > dist[j])) {
                    t = j;
                }
            }
            st[t] = true;

            //只有第一次加入的点距离是0x3f3f3f3f,如果不是第一次加入并且距离是0x3f3f3f3f,说明不是连通图
            if (i != 0 && dist[t] == 0x3f3f3f3f) {
                return 0x3f3f3f3f;
            }

            //如果不是第一个添加的点
            if (i != 0) {
                res += dist[t];
            }
            //先将dist[t]加进res中再更新,防止出现自环
            //更新其他点到最小生成树点集的最小距离
            for (int j = 1; j <= n; j++) {
                dist[j] = Math.min(dist[j], g[t][j]);
            }
        }
        return res;
    }
}

01 Kruskal算法求最小生成树

  • 题目

Snipaste_2023-03-16_23-43-33.png

  • 题解
import java.io.*;
import java.util.*;

public class Main {
    public static final int N = 100010;
    public static final int M = 200010;
    public static int[] p = new int[N];  //并查集的父节点数组
    public static Edge[] edges = new Edge[M];  //存储边
    public static int n, m;

    public static class Edge {
        public int a;
        public int b;
        public int w;

        public Edge(int a, int b, int w) {
            this.a = a;
            this.b = b;
            this.w = w;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
        String[] str1 = br.readLine().split(" ");
        n = Integer.parseInt(str1[0]);
        m = Integer.parseInt(str1[1]);
        for (int i = 0; i < m; i++) {
            String[] str2 = br.readLine().split(" ");
            int a = Integer.parseInt(str2[0]);
            int b = Integer.parseInt(str2[1]);
            int c = Integer.parseInt(str2[2]);
            edges[i] = new Edge(a, b, c);
        }

        int t = kruskal();
        if (t == 0x3f3f3f3f) {
            pw.println("impossible");
        } else {
            pw.println(t);
        }
        br.close();
        pw.close();
    }

    //并查集核心操作
    public static int find(int x) {
        if (p[x] != x) {
            p[x] = find(p[x]);
        }
        return p[x];
    }

    //返回最小生成树的权重和
    public static int kruskal() {
        //注意这里sort方法的写法
        Arrays.sort(edges, 0, m, (o1, o2) -> o1.w - o2.w);

        //初始化并查集
        for (int i = 1; i <= n; i++) {
            p[i] = i;
        }

        int res = 0;  //存最小生成树的权重和
        int cnt = 0;  //存当前的最小生成树内有几个点

        for (int i = 0; i < m; i++) {
            int a = edges[i].a;
            int b = edges[i].b;
            int w = edges[i].w;

            a = find(a);
            b = find(b);

            if (a != b) {
                cnt++;
                res += w;
                p[a] = b;
            }
        }

        //如果两个连通块不连通,则将这两个连通块合并
        if (cnt < n - 1) {
            return 0x3f3f3f3f;
        }
        return res;
    }
}