poj 2377 Bad Cowtractors(最大生成树)

来源:互联网 发布:ubuntu x screen分辨率 编辑:程序博客网 时间:2024/05/16 11:14

Bad Cowtractors
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 9317 Accepted: 3981

Description

Bessie has been hired to build a cheap internet network among Farmer John's N (2 <= N <= 1,000) barns that are conveniently numbered 1..N. FJ has already done some surveying, and found M (1 <= M <= 20,000) possible connection routes between pairs of barns. Each possible connection route has an associated cost C (1 <= C <= 100,000). Farmer John wants to spend the least amount on connecting the network; he doesn't even want to pay Bessie. 

Realizing Farmer John will not pay her, Bessie decides to do the worst job possible. She must decide on a set of connections to install so that (i) the total cost of these connections is as large as possible, (ii) all the barns are connected together (so that it is possible to reach any barn from any other barn via a path of installed connections), and (iii) so that there are no cycles among the connections (which Farmer John would easily be able to detect). Conditions (ii) and (iii) ensure that the final set of connections will look like a "tree".

Input

* Line 1: Two space-separated integers: N and M 

* Lines 2..M+1: Each line contains three space-separated integers A, B, and C that describe a connection route between barns A and B of cost C.

Output

* Line 1: A single integer, containing the price of the most expensive tree connecting all the barns. If it is not possible to connect all the barns, output -1.

Sample Input

5 81 2 31 3 72 3 102 4 42 5 83 4 63 5 24 5 17

Sample Output

42

题目大意:给出n个仓库,m条路,每条路说明了连接仓库的序号,以及路的长度。要求求将所有仓库连接起来的最大路长,不存在输出-1.

解题思路:和最小生成树的做法一样,每次加入最大边,用并查集判断边的两端是否已经连接,未连接加就加入,已连接就跳过。

#include <stdio.h>#include <string.h>#include <algorithm>#define N 10002using namespace std;struct coor{int x;int y;int value;}q[N * 2];int n, m, cnt, sum, far[N];int get(int x){return x != far[x]?far[x] = get(far[x]):x;}bool cmp(const coor &a, const coor &b){return a.value > b.value;}int main(){while (~scanf("%d%d", &n, &m)){memset(q, 0, sizeof(q));cnt = sum = 0;for (int i = 1; i <= n; i++)far[i] = i;for (int i = 0; i < m; i++)scanf("%d%d%d", &q[i].x, &q[i].y, &q[i].value);sort(q, q + m, cmp);for (int i = 0; i < m; i++)if (get(q[i].x) != get(q[i].y)){sum += q[i].value;cnt++;far[get(q[i].x)] = get(q[i].y);}if (cnt == n - 1)printf("%d\n", sum);elseprintf("-1\n");}return 0;}

原创粉丝点击