POJ-1258 最小生成树

本文介绍了一种使用PRIM算法结合二叉堆的数据结构实现最小生成树的方法,并通过具体代码展示了整个过程。该实现优化了算法效率,适用于解决大规模图论问题。

用了一下PRIM+二叉堆,开始时竟然和DIJKSTRA混了。

/*
 * hdu
 * mike-w
 * 2012-4-17
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 512
#define HEAP_SIZE 12345

#ifndef true
#define true 1
#endif

typedef struct _node
{
	int id,dst;
}node;

int f[MAX_SIZE][MAX_SIZE];
int tag[MAX_SIZE];
int N;
node heap[HEAP_SIZE];
int heap_size;

int swap(node* e1, node *e2)
{
	node tmp;
	memmove(&tmp,e1,sizeof(node));
	memmove(e1,e2,sizeof(node));
	memmove(e2,&tmp,sizeof(node));
	return 0;
}

int heap_in(int id, int dist)
{
	if(heap_size==HEAP_SIZE)
		return -1;
	heap_size++;
	heap[heap_size].id=id;
	heap[heap_size].dst=dist;
	int x=heap_size;
	int p=x/2;
	while(p>0 && heap[p].dst>heap[x].dst)
		swap(heap+p,heap+x),x=p,p/=2;
	return 0;
}

int heap_out(int *id, int *dist)
{
	if(heap_size==0)
		return -1;
	*id=heap[1].id;
	*dist=heap[1].dst;
	swap(heap+1,heap+heap_size);
	heap_size--;
	int p=1,x;
	int lc,rc;
	while(true)
	{
		lc=2*p;
		rc=2*p+1;
		x=p;
		if(lc<=heap_size && heap[lc].dst<heap[x].dst)
			x=lc;
		if(rc<=heap_size && heap[rc].dst<heap[x].dst)
			x=rc;
		if(x==p)
			break;
		swap(heap+x,heap+p);
		p=x;
	}
	return 0;
}

int prim(int source)
{
	memset(tag,0,sizeof(tag));
	heap_size=0;
	heap_in(source,0);
	int cost=0;
	int x,d,i;
	while(heap_out(&x,&d)!=-1)
	{
		if(tag[x])
			continue;
		tag[x]=1;
		cost+=d;
		for(i=0;i<N;i++)
			if(!tag[i])
				heap_in(i,f[x][i]);
	}
	return cost;
}

int main(void)
{
#ifndef ONLINE_JUDGE
	freopen("in","r",stdin);
#endif
	int i,j,cost,tmp;
	while(scanf("%d",&N)!=EOF)
	{
		for(i=0;i<N;i++)
			for(j=0;j<N;j++)
				scanf("%d",f[i]+j);
		cost=99999999;
		for(i=0;i<1;i++)
		{
			tmp=prim(i);
			if(tmp<cost)
				cost=tmp;
		}
		printf("%d\n",cost);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值