Problem Description
当前农村公路建设正如火如荼的展开,某乡镇政府决定实现村村通公路,工程师现有各个村落之间的原始道路统计数据表,表中列出了各村之间可以建设公路的若干条道路的成本,你的任务是根据给出的数据表,求使得每个村都有公路连通所需要的最低成本。
Input
连续多组数据输入,每组数据包括村落数目N(N <= 1000)和可供选择的道路数目M(M <= 3000),随后M行对应M条道路,每行给出3个正整数,分别是该条道路直接连通的两个村庄的编号和修建该道路的预算成本,村庄从1~N编号。
Output
输出使每个村庄都有公路连通所需要的最低成本,如果输入数据不能使所有村庄畅通,则输出-1,表示有些村庄之间没有路连通。
Sample Input
5 8
1 2 12
1 3 9
1 4 11
1 5 3
2 3 6
2 4 9
3 4 4
4 5 6
Sample Output
19
-
- 迪杰特斯拉算法,首先将所有的标记为最大值,然后对可以通行的道路进行赋值,从点1开始,寻找与点1相邻并且在
- 相邻点中距离点1最近的点,完成对点1标记已使用,然后将距离点1最近的点作为目标点,以此往复。使用的是一种
- 贪心算法,对于每次寻找路径,都回去寻找最短距离。
-
- #include <iostream>
- #include <algorithm>
- #include <queue>
- #include <cstring>
- #include <stdio.h>
- using namespace std;
- #define INF 0x3f3f3f3f
-
- int mp[1001][1001], lowc[1001], vis[1001];
- int n, m;
-
- int f(int mp[][1001], int n)
- {
- int minc, p, res = 0;
- int i, j;
- vis[1] = 1;
- for(i=1;i<=n;i++)
- {
- lowc[i] = mp[1][i];
- }
- for(i=1;i<n;i++)
- {
- minc = INF;
- for(j=1;j<=n;j++)
- {
- if(!vis[j] && lowc[j]<minc)
- {
- minc = lowc[j];
- p = j;
- }
- }
- if(minc == INF)
- {
- return -1;
- }
- res += minc;
- vis[p] = 1;
- for(j=1;j<=n;j++)
- {
- if(!vis[j]&&lowc[j]>mp[p][j])
- {
- lowc[j] = mp[p][j];
- }
- }
- }
- return res;
- }
- int main()
- {
- while(~scanf("%d %d", &n, &m))
- {
- int u, v, w;
- memset(vis,0,sizeof(vis));
- memset(mp, 0, sizeof(mp));
- memset(lowc, 0, sizeof(lowc));
- for(int i=1;i<=n;i++)
- {
- for(int j=1;j<=n;j++)
- {
- if(i == j)
- {
- mp[i][j] = 0;
- }
- else
- {
- mp[i][j] = INF;
- }
- }
- }
- while(m--)
- {
- cin>>u>>v>>w;
- if(mp[u][v]>w)
- {
- mp[u][v] = mp[v][u] =w;
- }
- }
- printf("%d\n",f(mp, n));
- }
- return 0;
- }
-