Constructing Roads(POJ-2421)(最小生成树)

  |  

There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
Input
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
Output
You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.
Sample Input
3
0 990 692

990 0 179

692 179 0

1

1 2

Sample Output
179

题意:
要修公路,输入一个n,表示n个村庄。接着输入n*n的矩阵,该图的邻接矩阵,然后输入一个q 接下来的q行,每行包含两个数a,b,表示a、b这条边联通,就是已经有公路不用修了,要让所有村庄联通在一起问:修路最小代价是多少。

思路:
这道题的话,根据题目输入构造邻接矩阵,然后把已经联通的村庄的距离设置为0,表示不用在修这条公路。然后用Prim算法即可。

AC代码:

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
70
71
72
73
74
75
#include <stdio.h>
#include <string>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
typedef long long ll;
const int maxx = 10010;
const int mod = 10007;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
using namespace std;
int mapp[maxx][maxx];
int dis[maxx];
bool vis[maxx];
int n;
void Prim()
{
int sum = 0;
int now;
for (int i = 1; i <= n; i++)
{
dis[i] = i;
vis[i] = false;
}
for (int i = 1; i <= n; i++)
dis[i] = mapp[1][i];
dis[1] = 0;
vis[1] = true;
for (int i = 1; i < n; i++)
{
now = inf;
int minn = inf;
for (int j = 1; j <= n; j++)
{
if (!vis[j] && dis[j] < minn)
{
now = j;
minn = dis[j];
}
}
if(now == inf)
break;
vis[now] = true;
sum += minn;
for (int j = 1; j <= n; j++)
{
if (!vis[j] && dis[j] > mapp[now][j])
dis[j] = mapp[now][j];
}
}
printf("%d\n", sum);
}
int main()
{
while (~scanf("%d", &n))
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &mapp[i][j]);
int q, a, b;
scanf("%d", &q);
for (int i = 1; i <= q; i++)
{
scanf("%d%d", &a, &b);
mapp[a][b] = mapp[b][a] = 0;
}
Prim();
}
return 0;
}

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
,
字数统计:87.6k 载入天数...载入时分秒...