zoukankan      html  css  js  c++  java
  • 洛谷P1546 最短网络 Agri-Net 题解 最小生成树/Prim算法

    题目链接:https://www.luogu.com.cn/problem/P1546

    题目大意:

    给你一个邻接矩阵,求它的最小生成树。

    解题思路:

    因为是邻接矩阵,用Prim算法求最小生成树写起来比较方便。

    实现代码如下:

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 110;
    int n, g[maxn][maxn], cost[maxn], ans;
    bool vis[maxn];
    int main() {
        cin >> n;
        for (int i = 0; i < n; i ++)
            for (int j = 0; j < n; j ++)
                cin >> g[i][j];
        memset(cost, -1, sizeof(cost));
        cost[0] = 0;
        for (int i = 0; i < n; i ++) {
            int id = -1;
            for (int j = 0; j < n; j ++)
                if (!vis[j] && cost[j] != -1 && (id == -1 || cost[id] > cost[j]))
                    id = j;
            vis[id] = true;
            ans += cost[id];
            for (int j = 0; j < n; j ++)
                if (!vis[j] && (cost[j] == -1 || g[id][j] < cost[j])) cost[j] = g[id][j];
        }
        cout << ans << endl;
        return 0;
    }
    
  • 相关阅读:
    temp12
    temp111
    test.c
    vipLogin.c
    services.c
    request.c
    managerLogin.c
    将博客搬至CSDN
    SpringMabatis整合项目mybatis-configuration.xml核心配置
    logback-test.xml配置文件模板
  • 原文地址:https://www.cnblogs.com/quanjun/p/12343239.html
Copyright © 2011-2022 走看看