您的位置:首页 > 其它

prim 最小生成树

2017-01-30 23:24 375 查看

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
4000
][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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: