Prim 算法求最小生成树

数据参考
百度经验
博客园 楠楠IT
测试接口 牛客 连通工程
问题背景
求国家建设公路的最小开销

算法思想
首先建立 邻接矩阵
然后 设定最小消耗顶点(就是两个定点之间的权重最小)顶点集合 U
每次从 矩阵中找出没有被访问过的点到已经在集合U中的点的距离的最小值,然后把这个顶点放入集合U中。

有任何问题请联系 [email protected]

#include <iostream>
#include <deque>
#include <fstream>
#include <vector>
using namespace std;

#ifdef debug
ifstream ifile("case2.txt");
#define cin ifile
#endif

#define Inf 10000000
int arc[101][101];// 连接矩阵
vector<bool> visited;// 标记是否访问过
int Prim(int vexnum, vector<int> &u)// 集合U
{
    long long sumMoney = 0;
    u.resize(1);
    u[0] = 0; // 表示从 0 出发遍历整幅图
    visited[0] = true;// 表示访问过
    while (u.size() != vexnum)
    {
        int min = Inf;// 找出值最小的边
        int nextAddPoint = -1;// 最小值所对应没有访问到的节点
        for (int i = 0; i < u.size(); i++)
        {
            for (int j = 0; j < vexnum; j++)
            {
                if (!visited[j] && arc[u[i]][j] < min)
                {
                    min = arc[u[i]][j];
                    nextAddPoint = j;
                }
            }
        }
        visited[nextAddPoint] = true;
        u.push_back(nextAddPoint);
        sumMoney += min;
    }
    return sumMoney;
}
int main()
{
    int vexnum, edge, money;
    cin >> money >> edge >> vexnum;
    int x, y, value;
    visited.resize(vexnum);
    for (int i = 0; i < vexnum; i++)// 初始化邻接矩阵
    {
        for (int j = 0; j < vexnum; j++)
        {
            arc[i][j] = Inf;
        }
        visited[i] = false;// 所有的节点标记为没有访问过
    }
    for (int i = 0; i < edge; i++)// 邻接矩阵赋值
    {
        cin >> x >> y >> value;
        x--; y--;
        if (value > arc[x][y])
            continue;
        arc[x][y] = value;
        arc[y][x] = arc[x][y];
    }

    vector<int> u;
    long long rlt = Prim(vexnum, u);
    if (rlt > money)
    {
        cout << "No" <<endl;
    }
    else
    {
        cout << "Yes" <<endl;
    }

    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/eat-too-much/p/9570213.html
今日推荐