MST——HDOJ 1102/1875

HDOJ 1102 Constructing Roads

/*
HDOJ 1102
MST基本应用
*/

#include <iostream>
using namespace std;

#define INF 2000
int graph[103][103];
int lowcast[103];
int find[103];
int N,sum;

void Prim(int v)
{
	int i,j,min,u;
	for(i=1;i<=N;i++)
	{
		find[i]=0;
		lowcast[i]=graph[v][i];
	}
	find[v]=1;
	for(i=1;i<=N;i++)
	{
		min=INF;
		for(j=1;j<=N;j++)
		{
			if(!find[j] && lowcast[j]<min)
			{
				min=lowcast[j];
				u=j;
			}
		}
		if(min == INF)
			return;
		find[u]=1;
		sum += min;

		for(j=1;j<=N;j++)
		{
			if(!find[j] && graph[u][j]<lowcast[j])
				lowcast[j]=graph[u][j];
		}
	}
}

int main()
{
	int i,j,m,a,b;
	while(scanf("%d",&N) != EOF)
	{
		for(i=1;i<=N;i++)
			for(j=1;j<=N;j++)
				cin>>graph[i][j];
		scanf("%d",&m);
		for(i=1;i<=m;i++)
		{
			scanf("%d%d",&a,&b);
			graph[a][b]=graph[b][a]=0;  //已经建好的就直接设为0加上也不影响结果
		}
		sum=0;
		Prim(1);
		printf("%d\n",sum);
	}
	return 0;
}

HDOJ 1875 畅通工程再续

/*
HDOJ 1875 畅通工程
MST,输入是用矩阵的,所以用Prim来做比较方便
*/

#include <math.h>
#include <iostream>
#include <iomanip>
using namespace std;

#define INF 9999999.9

struct land
{
	int x;
	int y;
}Land[101];

double graph[101][101];
int find[101];
double lowcast[101];
int C,count;
double sum;

void Prim(int v)
{
	int i,j,u;
	double min;
	for(i=0;i<C;i++)
	{
		find[i]=0;
		lowcast[i]=graph[v][i];
	}
	find[v]=1;
	for(i=1;i<C;i++)
	{
		min=INF;
		for(j=0;j<C;j++)
		{
			if(!find[j] && lowcast[j]<min)
			{
				min=lowcast[j];
				u=j;
			}
		}
		if(min == INF)
			return ;
		find[u]=1;
		sum += min;
		count++;
		for(j=0;j<C;j++)
		{
			if(!find[j] && graph[u][j]<lowcast[j])
				lowcast[j]=graph[u][j];
		}
	}
}

int main()
{
	int nCase,i,j,temp_1;
	double temp_2;
	cin>>nCase;
	while(nCase--)
	{
		cin>>C;
		for(i=0;i<C;i++)
		{
			cin>>Land[i].x>>Land[i].y;
		}
		
		for(i=0;i<C;i++)
		{
			graph[i][i]=0;
			for(j=i+1;j<C;j++)
			{
				temp_1=(Land[i].x-Land[j].x)*(Land[i].x-Land[j].x)
					+(Land[i].y-Land[j].y)*(Land[i].y-Land[j].y);
				
				temp_2=sqrt(double(temp_1));
				
				if(temp_2<10 || temp_2>1000)
					graph[i][j]=graph[j][i]=INF;
				else
					graph[i][j]=graph[j][i]=temp_2;
			}
		}
		sum=0.0;
		count=0;
		Prim(0);
		if(count == C-1)
		{
			sum=sum*100;
			cout<<setiosflags(ios::fixed);
			cout<<setprecision(1)<<sum<<endl;
		}
		else
			cout<<"oh!"<<endl;
	}	
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值