我的博客

codevs 1231 最优布线问题

目录
  1. AC 代码

题目描述 Description

学校需要将n台计算机连接起来,不同的2台计算机之间的连接费用可能是不同的。为了节省费用,我们考虑采用间接数据传输结束,就是一台计算机可以间接地通过其他计算机实现和另外一台计算机连接。

为了使得任意两台计算机之间都是连通的(不管是直接还是间接的),需要在若干台计算机之间用网线直接连接,现在想使得总的连接费用最省,让你编程计算这个最小的费用。

输入描述 Input Description

输入第一行为两个整数n,m(2<=n<=100000,2<=m<=100000),表示计算机总数,和可以互相建立连接的连接个数。接下来m行,每行三个整数a,b,c 表示在机器a和机器b之间建立连接的话费是c。(题目保证一定存在可行的连通方案, 数据中可能存在权值不一样的重边,但是保证没有自环)

输出描述 Output Description

输出只有一行一个整数,表示最省的总连接费用。

样例输入 Sample Input

3 3

1 2 1

1 3 2

2 3 1

样例输出 Sample Output

2

数据范围及提示 Data Size & Hint

最终答案需要用long long类型来保存

AC 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <algorithm>
using namespace std;


int fa[1000006];
struct linkx {
int x, y, c;

} ls[1000006];

bool operator < (const linkx &a, const linkx &b) {
return a.c < b.c;
}

int getfa(int x) {
return x == fa[x]? x: fa[x] = getfa(fa[x]);
}

void merge(int x, int y) {
fa[getfa(x)] = getfa(y);
}


int main() {
ios::sync_with_stdio(false);
int n, m;
cin >> n;
for (int i = 1; i <= n; i++) fa[i] = i;
cin >> m;
for (int i = 0; i < m; i++) {
cin >> ls[i].x >> ls[i].y >> ls[i].c;
}
sort(ls, ls+m);
long long cost = 0;
for (int i = 0; i < m; i++) {
if (getfa(ls[i].x) != getfa(ls[i].y)) {
merge(ls[i].x, ls[i].y);
cost += ls[i].c;
}
}
cout << cost << endl;
}

评论无需登录,可以匿名,欢迎评论!