http://acm.hdu.edu.cn/showproblem.php?pid=1233
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
Hint Hint Huge input, scanf is recommended.
- 这道题感觉还是挺不错的,刚学MST,代码也是乱敲的,根据MST概念用优先队列自己实现了一把,没想到一遍过,心情还是挺不错。时间限制4s,并且提示要用scanf,但我用cin+prim(优先队列实现)只用了1s。那么猜测这道题应该是用来卡kruskal(我也没学,先学了prim)。最小生成树还是蛮好理解的。
- Prim(优先队列):从第一个点开始,将它连接的所有点加入队列。取top点标记为1,加权值,然后再把top点连接的所有点加入队列,执行以上操作。注意有可能top点可能已经在之前被访问过,所以在遇到被访问过点的时候就跳过。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
#include<algorithm>
#include<cmath>
#include<map>
#include<queue>
#include<time.h>
using namespace std;
const int maxn = 1e4 + 5;;
const int INF = 0x3f;
bool vis[maxn];
int Max[maxn];
struct node {
int w, to;
bool operator <(const node& a)const {
return w > a.w;
}
};
vector<node>vec[maxn];
int ans = 0;
void Prim() {
priority_queue < node > p;
ans = 0;
p.push(vec[1][0]);
vis[1] = 1;
int id = 1;
while (!p.empty()) {
p.pop();
for (int i = 0; i <vec[id].size() ; i++) {
if (!vis[vec[id][i].to]) {
p.push(vec[id][i]);
}
}
if (p.empty())break;
id = p.top().to;
// cout << id << endl;
while (vis[id]&&!p.empty()) {
p.pop();
if (p.empty())break;
id = p.top().to;
}
if (p.empty())break;
vis[id] = 1;
ans += p.top().w;
}
return;
}
int main() {
int n;
while (cin >> n&&n) {
for (int i = 0; i < maxn; i++) {
vec[i].clear();
}
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n*(n-1)/2; i++) {
int A, B, C;
cin >> A >> B >> C;
node Q;
Q.to = B, Q.w = C;
vec[A].push_back(Q);
Q.to = A;
vec[B].push_back(Q);
}
Prim();
cout << ans << endl;
}
return 0;
}