prim算法

#include<iostream>
using namespace std;
#include<stdio.h>
const int maxn=100;
bool s[maxn];
int lowcost[maxn];
int closest[maxn];
int c[maxn][maxn];
void prim(int n)
{
    int total=0;
    s[1]=true;
    for(int i=2;i<=n;i++)//首先对三个数组进行初始化
    {
        lowcost[i]=c[1][i];
        closest[i]=1;
        s[i]=false;
    }
    printf("the MST is :\n");
    for(int i=1;i<=n-1;i++)//然后的工作就是添加n-1条边
    {
        int minn=10000;
        int j=1;
        for(int k=2;k<=n;k++)//选出最小的边
        {
            if(minn>lowcost[k]&&!s[k])
            {
                minn=lowcost[k];
                j=k;
            }
        }
        printf("%d %d %d\n",j,closest[j],lowcost[j]);
        total+=lowcost[j];
        s[j]=true;
        for(int k=2;k<=n;k++)//更新lowest和closest数组
        {
            if((c[j][k]<lowcost[k])&&!s[k])
            {
                lowcost[k]=c[j][k];
                closest[k]=j;
            }
        }
    }
    printf("the total price is:%d\n",total);
}
int main()
{
    int n;
    scanf("%d",&n);//输入n的值
    for(int i=1;i<=n;i++)//就是对数组c进行更新
        for(int j=i;j<=n;j++)
    {
        int temp;
        scanf("%d",&temp);
        c[i][j]=temp;
        c[j][i]=temp;
    }
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
    {
        printf("%d ",c[i][j]);
        if(j==n)
            printf("\n");
    }
    prim(n);
    return 0;


}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Prim算法是一种贪心算法,用于求解加权无向图的最小生成树。从一个节点开始,每次选择一个与当前生成树相邻的最小边,加入生成树中,直到所有节点都被加入生成树。下面是Prim算法的伪代码: ``` 1. 选取一个起始节点u 2. 标记节点u为已访问 3. for v in u的邻居节点: 4. 将(u,v)加入候选边集合中 5. while 候选边集合不为空: 6. 从候选边集合中选择一条最小边(u,v),将v标记为已访问 7. 将(u,v)加入生成树中 8. for w in v的邻居节点: 9. 如果w未被访问过,将(v,w)加入候选边集合中 ``` 下面是一个示例代码,使用邻接矩阵来表示图: ```python import sys def prim(graph): n = len(graph) # 初始化 visited = [False] * n dist = [sys.maxsize] * n parent = [-1] * n dist[0] = 0 for i in range(n): # 找到未访问过的最近的节点 u = -1 for j in range(n): if not visited[j] and (u == -1 or dist[j] < dist[u]): u = j # 标记为已访问 visited[u] = True # 更新与节点u相邻的节点的距离 for v in range(n): if not visited[v] and graph[u][v] != 0 and graph[u][v] < dist[v]: dist[v] = graph[u][v] parent[v] = u return parent # 示例代码 if __name__ == '__main__': graph = [ [0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [0, 3, 0, 0, 7], [6, 8, 0, 0, 9], [0, 5, 7, 9, 0] ] parent = prim(graph) for i in range(1, len(parent)): print("{}-{}".format(parent[i], i)) ``` 输出结果为: ``` 0-1 1-2 0-3 1-4 ``` 其中,输出的每一行表示生成树中的一条边,如“0-1”表示0和1之间有一条边。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值