[HDU] [1102] Constructing Roads

Problem Description

Loading...

Problem Analysis

A Minimum Spanning Tree Template problem

The distances between villages are first given in matrix form
Then the pairs of villages whose roads are already connected are given
At this point, just set the distance between these two villages to 0

ccpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<stdio.h>
#include<algorithm>
using namespace std;
int dis[120];
int e[120][120];
bool flag[120];
int inf=99999999;
int main() {
	int n;
	while(scanf("%d",&n)!=EOF) {
		for(int i=1; i<=n; i++) {
			dis[i]=inf;
			flag[i]=false;
		}
		for(int i=1; i<=n; i++) {
			for(int j=1; j<=n; j++) {
				e[i][j]=inf;
			}
		}

		for(int i=1; i<=n; i++) {
			for(int j=1; j<=n; j++) {
				int t;
				scanf("%d",&t);
				e[i][j]=t;
			}
		}
		int m;
		scanf("%d",&m);
		while(m--) {
			int ts,te;
			scanf("%d %d",&ts,&te);
			e[ts][te]=e[te][ts]=0;
		}
		int sum=0;
		dis[1]=0;
		bool x=true;
		while(true) {
			int v=-1;
			for(int u=1; u<=n; u++) {
				if(!flag[u]&&(v==-1||dis[u]<dis[v]))
					v=u;
			}
			if(v==-1)
				break;
			else {
				flag[v]=true;
				sum+=dis[v];
				for(int u=1; u<=n; u++) {
					dis[u]=min(dis[u],e[v][u]);
				}
			}
		}
		printf("%d\n",sum);
	}
	return 0;
}

Problem link: HDU 1102 Constructing Roads

Loading...