Prim算法(C/C++)

/* test data1 */
/* 输入 */
7 12 0    // 顶点数、边数、起始点
0 1 2
0 3 1
1 3 3
1 4 10
2 0 4
2 5 5
3 2 2
3 4 2
3 5 8
3 6 4
4 6 6
6 5 1
/* 输出 */
12
/* test data2 */
/* 输入 */
4 5 3    // 顶点数、边数、起始点
0 1 2
0 2 4
0 3 1
1 3 2
2 3 3
/* 输出 */
6
#include <iostream>
#include <vector>

int Prim(const std::vector<std::vector<int>> &, int);
void buildGraph(std::vector<std::vector<int>> &, int);
int main()
{
    int vertexNum, edgeNum, source;
    std::cin >> vertexNum >> edgeNum >> source;
    std::vector<std::vector<int>> MGraph(vertexNum, std::vector<int>(vertexNum, __INT_MAX__));
    buildGraph(MGraph, edgeNum);

    int MINLen = Prim(MGraph, source);
    std::cout << MINLen;

    return 0;
}
void buildGraph(std::vector<std::vector<int>> & MGraph, int edgeNum)
{
    for (int v1, v2, weight, i = 0; i != edgeNum; ++i)
    {
        std::cin >> v1 >> v2 >> weight;
        MGraph[v1][v2] = MGraph[v2][v1] = weight;
    }
    for (int i = 0; i != MGraph.size(); ++i)
        MGraph[i][i] = 0;
}
int Prim(const std::vector<std::vector<int>> &MGraph, int MST)
{

    int MSTLen{0}, count{0}, guard{-1};
    std::vector<int> dist{MGraph[MST]}, path(MGraph.size(),-1);
    for (int i = 0; i != MGraph.size(); ++i)
        if (MGraph[MST][i] != __INT_MAX__)
            path[i] = MST;
    for ( ; guard != MST; ++count)
    {
        guard = MST;
        for (int temp{__INT_MAX__}, j = 0; j != MGraph.size(); ++j)
            if (dist[j] != __INT_MAX__ && dist[j] && dist[j] < temp)
            {
                temp = dist[j];
                MST = j;
            }
        MSTLen += dist[MST];
        dist[MST] = 0;
        for (int k = 0; k != MGraph.size(); ++k)
            if (MGraph[MST][k] != __INT_MAX__ && dist[k] && MGraph[MST][k] < dist[k])
            {
                dist[k] = MGraph[MST][k];
                path[k] = MST;
            }
    }
    if (count == MGraph.size())
        return MSTLen;
    return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值