[HDU] [1251] Jungle Roads

Problem Description

Loading...

Problem Analysis

Knowing it’s a Minimum Spanning Tree
I’m too lazy to translate the problem statement sentence by sentence again…

From the problem description
Using Prim is better here
because the number of villages is relatively small
…just a quick complaint
I’ve seen this a lot by now
my English has really gotten much better
and a quick scan really lets me more or less understand it

Here I use an array and directly store via characters minus ‘A’

Also, the input data here involves characters, spaces, newlines, and such—it’s a bit of a trap…
Well… I should say it’s a big trap…
The algorithm itself is perfectly fine… but I got stuck on the input data and couldn’t move…
That’s missing the point!

cpp
 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
58
59
60
61
62
63
64
65
66
67
68
69
#include<stdio.h>
#include<algorithm>
using namespace std;
int main() {
	int dis[27];
	int e[27][27];
	bool flag[27];
	int N,inf=999999;
	while(scanf("%d",&N),N) {
		getchar();
		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++) {
			char c;
			int n;
			scanf(" %c %d",&c,&n);
			while(n--) {
				char c2;
				int t2;
				scanf(" %c %d",&c2,&t2);
				e[c-'A'+1][c2-'A'+1]=t2;
				e[c2-'A'+1][c-'A'+1]=t2;
			}
		}
		/*
		这种输入方法POJ会超时……
		不过杭电可以过 
		        for(int i=1; i<N; i++) {
		            char c;
		            int n;
		            scanf("%c %d",&c,&n);
		            while(n--) {
		                char c2;
		                int t2;
		                getchar();
		                scanf("%c %d",&c2,&t2);
		                e[c-'A'+1][c2-'A'+1]=t2;
		                e[c2-'A'+1][c-'A'+1]=t2;
		            }
		            getchar();
		        }
		*/
		int sum=0;
		dis[1]=0;
		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;
			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】[1301]Jungle Roads
【POJ】[1251]Jungle Roads

Loading...