HDU 1102/POJ 2421 Constructing Roads(MST&Prim优化)

来源:互联网 发布:js 观察者模式 实例 编辑:程序博客网 时间:2024/05/22 10:47
Constructing Roads
http://acm.hdu.edu.cn/showproblem.php?pid=1102
http://poj.org/problem?id=2421

Description

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

30 990 692990 0 179692 179 011 2

Sample Output

179

题意:
裸MST,但有部分通路,这里我们将其处理为距离=0就是~

思路:
说一下怎么把Prim算法复杂度从O(N^3)优化到O(N^2):
用一个数组lowcost记录每个点到其他点的最短边。
一开始只知道A到各点的距离,所以lowcost[i] = dis[0][i]
接下来的n-1次循环分两步:
1. 找到剩下的未访问点中lowcost最小的点k:
for (j = 1; j < n; j++)if (!visited[j] && lowcost[j]<min){min = lowcost[j];k = j;}ans += min;visited[k] = true;
2. 通过点k更新所有lowcost:
for (j = 1; j < n; j++)if (!visited[j] && dis[k][j]<lowcost[j])lowcost[j] = dis[k][j];

完整代码:
/*HDU: 0ms,268KB*//*POJ: 0ms,184KB*/#include<cstdio>#include<cstring>using namespace std;const int maxn=101;const int inf = 100001;//okint n;int dis[maxn][maxn];int lowcost[maxn];bool visited[maxn];int prim(){memset(visited, 0, sizeof(visited));int i, j, min, k = 0, ans = 0;for (i = 1; i < n; i++)lowcost[i] = dis[0][i];visited[0] = true;for (i = 1; i < n; i++){min = inf;for (j = 1; j < n; j++)if (!visited[j] && lowcost[j]<min){min = lowcost[j];k = j;//printf("%d ",min);}//else               // printf("    ");ans += min;visited[k] = true;for (j = 1; j < n; j++)if (!visited[j] && dis[k][j]<lowcost[j])lowcost[j] = dis[k][j];//printf("\n");}return ans;}int main(){int i, j;while (~scanf("%d", &n)){for (i = 0; i < n; i++)for (j = 0; j < n; j++)scanf("%d", &dis[i][j]);int m, a, b;scanf("%d", &m);while(m--){scanf("%d%d", &a, &b);dis[a - 1][b - 1] = dis[b - 1][a - 1] = 0;//已修路,要修的距离为0}printf("%d\n", prim());}return 0;}



原创粉丝点击