{POJ}{2421}{Constructing Roads}{Prim}

基本MST思路

#include<iostream>

using namespace std;

#define MAX 10000

#define INF 999999

int g[MAX][MAX],visit[MAX],dist[MAX];

int nv,ne,sum;

int prim()

{

	int i,j,tmp,mark_pos,mark_min;

	sum = 0;

	for(i = 1;i<=nv;++i)

	{

		dist[i] = INF;

		visit[i] = 0;

	}

	dist[1] = 0;

	for(i=1;i<=nv;++i)

	{

		mark_min = INF;

		for(j=1;j<=nv;++j)

			if(!visit[j]&&mark_min>dist[j])

			{

				mark_min = dist[j];

				mark_pos = j;

			}

		visit[mark_pos] = 1;

		sum+=dist[mark_pos];

		for(j=1;j<=nv;++j)

			if(!visit[j]&&dist[j] > g[mark_pos][j])

				dist[j] = g[mark_pos][j];

	}

	return sum;

}

int main()

{

	int i,j,tmp,b,a;

	scanf("%d",&nv);

	for(i=1;i<=nv;++i)

		for(j=1;j<=nv;++j)

			scanf("%d",&g[i][j]);

	scanf("%d",&ne);

	for(i=1;i<=ne;++i)

	{

		scanf("%d%d",&a,&b);

		g[a][b] = g[b][a] = 0;

	}

	tmp = prim();

	printf("%d\n",tmp);

 

你可能感兴趣的:(struct)