Constructing Roads

hdu1102

将已经有路的城市初始化为0

#include<iostream>
#include<cstring>
#define N 110
#define INF 0x3f3f3f3f

using namespace std;
int n;
int e[N][N],dis[N],flag[N];


int main()
{
	while(cin>>n)
	{
		if(n==0)break;
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
				scanf("%d",&e[i][j]);
		int m;
		cin>>m;
		for(int i=1;i<=m;i++)
		{
			int x,y;
			cin>>x>>y;
			e[x][y] = e[y][x] = 0;
		}
		
		
		int sum =0;
		for(int i=1;i<=n;i++)
			dis[i] = e[1][i];
		memset(flag,0,sizeof(flag));
		flag[1] = 1;
		for(int i=1;i<n;i++)
		{
			int minn = INF;
			int u;
			for(int j=1;j<=n;j++)
				if(flag[j]==0&&dis[j]<minn)
				{
					minn = dis[j];
					u = j;
				}
			flag[u] = 1;
			sum = sum +dis[u];
			for(int k=1;k<=n;k++)
				if(flag[k]==0&&dis[k]>e[u][k])
					dis[k] = e[u][k];			
		}
		cout<<sum<<endl;
	}
	
}

上一篇:[kuangbin带你飞]专题六 最小生成树


下一篇:LeetCode 174. Dungeon Game (C++)