[CCF]最优灌溉
Question
雷雷承包了很多片麦田,为了灌溉这些麦田,雷雷在第一个麦田挖了一口很深的水井,所有的麦田都从这口井来引水灌溉。
为了灌溉,雷雷需要建立一些水渠,以连接水井和麦田,雷雷也可以利用部分麦田作为“中转站”,利用水渠连接不同的麦田,这样只要一片麦田能被灌溉,则与其连接的麦田也能被灌溉。
现在雷雷知道哪些麦田之间可以建设水渠和建设每个水渠所需要的费用(注意不是所有麦田之间都可以建立水渠)。请问灌溉所有麦田最少需要多少费用来修建水渠。
输入的第一行包含两个正整数n, m,分别表示麦田的片数和雷雷可以建立的水渠的数量。麦田使用1, 2, 3, ……依次标号。 接下来m行,每行包含三个整数ai, bi, ci,表示第ai片麦田与第bi片麦田之间可以建立一条水渠,所需要的费用为ci。
输出一行,包含一个整数,表示灌溉所有麦田所需要的最小费用。
Input
4 4
1 2 1
2 3 4
2 4 2
3 4 3
Output
6
建立以下三条水渠:麦田1与麦田2、麦田2与麦田4、麦田4与麦田3。
Solution
// http://118.190.20.162/view.page?gpid=T18
#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cstring>
#include<string>
#include<climits>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<set>
#include<cctype>
#include<map>
#include<utility>
using namespace std;
#define print(A) cout << #A << ": "<< A << endl;
#define inf 0x3fffffff
int node_num, edge_num;
vector<int> parent;
int findRoot(int node) { return node == parent[node]? node: findRoot(parent[node]); }
struct edge {
int node1, node2, dist;
edge(int n1, int n2, int d): node1(n1), node2(n2), dist(d) {}
bool operator<(const edge& another) const { return this->dist > another.dist; }
};
int main() {
cin >> node_num >> edge_num;
parent.resize(node_num+1);
priority_queue<edge> pq;
for (int i = 1; i <= edge_num; i++) {
int node1, node2, dist;
cin >> node1 >> node2 >> dist;
pq.push(edge(node1, node2, dist));
}
for (int i = 1; i <= node_num; i++) parent[i] = i;
int res = 0;
while (!pq.empty()) {
edge temp = pq.top(); pq.pop();
int node1 = temp.node1;
int node2 = temp.node2;
int node1_root = findRoot(node1);
int node2_root = findRoot(node2);
if (node1_root != node2_root) {
parent[node1_root] = node2_root;
parent[node1] = node2_root;
res += temp.dist;
}
}
cout << res << endl;
}
思路:使用并查集实现最小生成树板子。