poj 2377 Bad Cowtractors(最大生成树模板)

来源:互联网 发布:皮卡丘漫画软件 编辑:程序博客网 时间:2024/04/29 18:20

题目链接:点击打开链接

Bad Cowtractors
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 12848 Accepted: 5330

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

 

题意:求出最大生成树

思路:可以用prim或者kruskal来做,用prim记得判重,取最大的那一条。 kruskal因为有个排序操作,会优先取到满足你条件的那一条,所以不需要特判。后面的因为已经连通所以不予考虑。

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>using namespace std;#define N 1010#define M 20010int n,m;int pre[N];struct Edge{    int u,v,w;} e[M];void init(){    for(int i=0; i<=n; i++)        pre[i]=i;}bool cmp(Edge a,Edge b){    return a.w>b.w;}int finds(int x){    int r=x;    while(r!=pre[r])        r=pre[r];    int j;    while(x!=pre[x])    {        j=x;        x=pre[x];        pre[j]=r;    }    return r;}int kruskal(){    int ans=0;    int x,y;    for(int i=0; i<m; i++)    {        x=finds(e[i].u);        y=finds(e[i].v);        if(x==y) continue;        pre[x]=y;        ans+=e[i].w;    }    int num=0;    for(int i=1; i<=n; i++)        if(pre[i]==i)            num++;    if(num>1)        return -1;    return ans;}int main(){    while(~scanf("%d %d",&n,&m))    {        init();        for(int i=0; i<m; i++)                scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w);        sort(e,e+m,cmp);        printf("%d\n",kruskal());    }    return 0;}


 

 

 

 

0 0
原创粉丝点击