1212 . 无向图最小生成树
基准时间限制:1 秒 空间限制:65536 KB 分值: 0
N个点M条边的有向连通图,每条边有一个权值,求该图的最小生成树。
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000) 第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Input 示例
9 14 1 2 4 2 3 8 3 4 7 4 5 9 5 6 10 6 7 2 7 8 1 8 9 7 2 8 11 3 9 2 7 9 6 3 6 4 4 6 14 1 8 8
Output 示例
37
如果你已经搞定了该问题,或许可以再看看:
二维曼哈顿距离最小生成树 | 分值: 160 |
编号 | 相关问题 | 分值 |
1076 | 2条不相交的路径 | 40 |
1078 | 3条不相交的路径 | 1280 |
1077 | 3条不相交的路径 | 80 |
1213 | 二维曼哈顿距离最小生成树 | 160 |
最小生成树(Dijkstra)模板。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long LL;
const int maxN = 1000 + 10;
const int maxM = 50000 + 10;
int n, m;
struct EE{
int s, e, v;
friend bool operator < (const EE a, const EE b){
return a.v>b.v;
}
};
EE x;
int fa[maxN];
void initset(){
for(int i=0; i<=n; i++) fa[i] = i;
}
int findset(int x){
if( x==fa[x] ) return x;
else return fa[x] = findset(fa[x]);
}
void unionset(int x, int y){
x = findset(x);
y = findset(y);
if( x<y ) fa[y] = x;
else fa[x] = y;
}
priority_queue<EE> q;
int main(){
while( EOF != scanf("%d%d", &n, &m) ){
for(int i=0; i<m; i++){
scanf("%d%d%d", &x.s, &x.e, &x.v);
q.push(x);
}
initset();
x = q.top(); q.pop();
LL ans = x.v; fa[0] = 2;
unionset(x.s, x.e);
while( n!=fa[0] ){
x = q.top(); q.pop();
if( findset(x.s) != findset(x.e) ){
ans += x.v; fa[0]++;
unionset(x.s, x.e);
}
}
printf("%lld\n", ans);
}
return 0;
}