Problem Description
某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度。
Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
Sample Output
3
5
HintHint
Huge input, scanf is recommended.
[分析]
首先分析点和边的数量。
边是n*(n-1)/2,即为完全图,所以是稠密图,用prim。(实际数据好像并没有这么多,运行了200+ms,排行榜上有10+ms的,就差比较多,但是prim还是一个好算法)
很久以前就想过用优先队列来优化prim但是一直没有去实现。刚好今天遇到这一题。
就是把一个点的所有边push入优先队列,pop出最短的边,就可以找出下一个要去的点,在把这个点的所有边push入队列,再pop,不断循环直至所有点都联通。
[代码]
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
int vis[115];
struct Node
{
int to,cos;
friend bool operator < (Node a, Node b)
{
return a.cos > b.cos;
}
}no;
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
if (!n)break;
if (n == 1)
{
printf("0\n");
continue;
}
vector<Node>v[105];
priority_queue<Node>q;
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n*(n - 1) / 2; i++)
{
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
no.to = y;
no.cos = z;
v[x].push_back(no);
no.to = x;
v[y].push_back(no);
}
no.cos = 0; no.to = 1;
q.push(no);
int ans = 0;
int cnt = 0;
while (!q.empty())
{
no = q.top();
q.pop();
if (vis[no.to] == 0)
{
vis[no.to] = 1;
ans += no.cos;
cnt++;
if (cnt == n)
{
printf("%d\n", ans);
break;
}
for (int i = 0; i < v[no.to].size(); i++)
{
if(!vis[v[no.to][i].to])q.push(v[no.to][i]);
}
}
}
}
}