prim 最小生成树

10 篇文章 0 订阅
7 篇文章 0 订阅

prim 最小生成树

从单一顶点开始,普里姆算法按照以下步骤逐步扩大树中所含顶点的数目,直到遍及连通图的所有顶点。

  • 输入:一个加权连通图,其中顶点集合为V,边集合为E;
  • 初始化:Vnew = {x},其中x为集合V中的任一节点(起始点),Enew = {};
  • 重复下列操作,直到Vnew = V:
  • 在集合E中选取权值最小的边(u, v),其中u为集合Vnew中的元素,而v则是V中没有加入Vnew的顶点(如果存在有多条满足前述条件即具有相同权值的边,则可任意选取其中之一);
  • 将v加入集合Vnew中,将(u, v)加入集合Enew中;
    输出:使用集合Vnew和Enew来描述所得到的最小生成树。
    这里写图片描述
    使用优先队列优化后复杂度为o(|E|log|V|)。

把33行代码改一下就是Dijkstral了,有木有///
e.from=t,e.to=i,e.val=cost[t][i]+val;

传送门》》问题链接

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
int cost[26][26];
int V;
bool used[26];
struct edge{int from,to,val;}e;//val: from 到 to的距离值

bool operator <(edge x,edge y){
    return x.val>y.val;
}

int prim(){
    memset(used,0,sizeof(used));
    priority_queue<edge> que;
    cost[0][0]=e.from=e.to=e.val=0;
    que.push(e);
    int res=0;

    while(!que.empty()){
        e=que.top();que.pop();
        int f=e.from,t=e.to,val=e.val;
        if(used[t]) continue;
        used[t]=true;
        res+=cost[f][t];
//        printf("--%c->%c\n",(char)(f+'A'),(char)(t+'A'));

        for(int i=0;i<26;i++)
            if(!used[i]&&cost[t][i]!=INF){
                e.from=t,e.to=i,e.val=cost[t][i];
                que.push(e);
            }
    }
    return res;
}

int main()
{
    while(~scanf("%d",&V)&&V){
        memset(cost,0x3f,sizeof(cost));
        int N,val;char a[2],b[2];
        for(int i=0;i<V-1;i++){
            scanf("%s%d",a,&N);
            if(N<=0) continue;
            int x=*a-'A';
            while(N--){
                scanf("%s%d",b,&val);
                int y=*b-'A';
                cost[x][y]=cost[y][x]=val;
            }
        }
        printf("%d\n",prim());
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值