POJ 1251

题意:给出一个n,以邻接表的形式给出n个点与其他点相连的距离,求最小生成树

思路:prim + 优先队列

#include<cmath>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<ctype.h>
#include<queue>
using namespace std;
const int qq=1000+5;
int head[qq];
int vis[30];
int tot,n;
struct Edge
{
	int to,w,next;
	bool operator < (const Edge a)const
	{
		return w>a.w;
	}
}edge[qq*2];
void Add(int u,int v,int w)
{
	edge[tot].to=v;
	edge[tot].w=w;
	edge[tot].next=head[u];
	head[u]=tot++;
}
void Prim()
{
	priority_queue<Edge>Q;
	int minx=0;
	Edge now,cur;
	now.w=0;now.to=1;
	Q.push(now);
	while(!Q.empty()){
		now=Q.top();
		Q.pop();
		int to=now.to;
		if(vis[to])	continue;
		int w=now.w;
		minx+=w;
		vis[to]=1;
		for(int i=head[to]; i!=-1; i=edge[i].next){
			if(!vis[edge[i].to])
				Q.push(edge[i]);
		}
	}
	printf("%d\n",minx);
}
int main()
{
	while(scanf("%d",&n)!=EOF){
		if(n==0)	break;
		n--;
		memset(head,-1,sizeof(head));
		memset(vis,0,sizeof(vis));
		char s[5];int m;
		for(int i=0; i<n; ++i){
			scanf("%s%d",s,&m);
			int x=s[0]-'A'+1,y,w;
			for(int j=0; j<m; ++j){
				scanf("%s%d",s,&w);
				y=s[0]-'A'+1;
				Add(x,y,w);Add(y,x,w);
			}
		}
		Prim();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值