最小生成树c++

什么是最小生成树

https://zhuanlan.zhihu.com/p/136387766

代码

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
int father[1000], n, m;
void init() {
    for(int i = 0; i < 1000; i++) {
        father[i] = i;
    }
}

int find(int x) {
    return x == father[x] ? x : father[x] = find(father[x]);
}




struct edge
{
    int u, v, w;
    bool operator < (const edge& E) {
        return w < E.w;
    }
};

//bool cmp(const edge& e1, const edge& E) {
    //return e1.w < E.w;
//} 

vector<edge> graph;

int kruskal() {
    
    sort(graph.begin(), graph.end());
    
    //用来标记最小生成树什么时候结束循环(当sign = n - 1时候结束循环)
    int sign = 0;
    //标记生成树中所有的路径的和
    int ans = 0;
    for(int i = 0; i < m; i++) {
        int u = graph[i].u, v = graph[i].v, w = graph[i].w;
        
        u = find(u), v = find(v);
        
        if(u == v) {
            continue;
        }

        father[u] = v;

        sign++;
        ans += w;
        
        if(sign == n - 1) {
            break;
        }
    }
    if(sign != n - 1) {
        
        return -1;
    }
    return ans;
}

int main(int argc, char const *argv[])
{
    system("chcp 65001");
    cin >> n >> m;
    graph.resize(m);
    for(int i = 0; i < m; i++) {
        cin >> graph[i].u >> graph[i].v >> graph[i]. w;
    }
    init();
    int a = kruskal();
    if(a == -1) {
        cout << "没有最小生成树" << endl;
    }else {
        cout << a <<endl;
    }
    return 0;
}

结果展示

该图为

输入为

posted @ 2023-08-27 18:59  铜锣湾陈昊男  阅读(9)  评论(0)    收藏  举报