poj2421(prim算法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26760433/article/details/84857328

我习惯用邻接表存储图,这题虽然给的是邻接矩阵,我是转化为邻接表,结果一直WA ╮(╯﹏╰)╭。只好改用邻接矩阵写。这题就是最小生成树的一点变形,最后给的顶点说明已经建好路了,将两点之间的距离置为0即可。

贴代码

// 228k  125ms
#include<iostream>
#include<queue>
using namespace std;
int n;
int map[105][105];
int mark[105];
class Dist
{
public:
	int index;
	int pre;
	int length;
	friend bool operator<(const Dist &a,const Dist &b)
	{
		return a.length>b.length;
	}
};

void prim(int s)
{
	int ans = 0;
	int i,j;
	Dist * D= new Dist[n+1];
	for(i=1;i<=n;i++)
	{
		D[i].index=i;
		D[i].length = 1<<30;
		D[i].pre= s;
	}
	priority_queue<Dist> aqueue;
	int now_node=s;

	for(i=1;i<n;i++)
	{
		mark[now_node]=1;
		for(j=1;j <=n;j++ )
		{
			if(mark[j]==0 && D[j].length>map[now_node][j])
			{
				D[j].length = map[now_node][j];
				D[j].pre = now_node;
				aqueue.push(D[j]);
			}
		}
		Dist d;
		while(!aqueue.empty())
		{
			d=aqueue.top();
			aqueue.pop();
			if(mark[d.index]==0)
				break;
		}

		now_node = d.index;
		ans = ans+d.length;
	}
	cout<<ans<<endl;
}

int main()
{
	int i,j;
	int w;
	cin>>n;
	for( i=1;i<=n;i++)
	{
		for( j=1;j<=n;j++)
		{
			cin>>w;
			if(j>=i)
				continue;
			map[i][j]=map[j][i]=w;
		}
	}
		
	int q;
	int a,b;
	cin>>q;
	for(i=1;i<=q;i++)
	{
		cin>>a>>b;
		map[a][b] =map[b][a] = 0;    //距离置为0
	}
	
	prim(1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_26760433/article/details/84857328
今日推荐