• POJ 2377 Bad Cowtractors( 最小生成树转化 )



    **链接:****传送门 **

    题意:给 n 个点 , m 个关系,求这些关系的最大生成树,如果无法形成树,则输出 -1

    思路:输入时将边权转化为负值就可以将此问题转化为最小生成树的问题了


    /*************************************************************************
        > File Name: poj2377.cpp
        > Author:    WArobot 
        > Blog:      http://www.cnblogs.com/WArobot/ 
        > Created Time: 2017年06月19日 星期一 18时38分35秒
     ************************************************************************/
    
    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    using namespace std;
    
    const int MAX_N = 1010;
    const int MAX_M = 20010;
    struct edge{
    	int from , to ,cost;
    }E[MAX_M];
    
    int n , m;
    int par[MAX_N];
    
    void init_union_find_set()	{ for(int i = 0 ; i < MAX_N ; i++) par[i] = i; }
    int  find(int x)			{ return x == par[x] ? x : par[x] = find(par[x]); }
    bool same(int x,int y)		{ return find(x) == find(y); }
    void union_set(int x,int y) { x = find(x); y = find(y);	if(x!=y) par[y] = x; }
    
    bool cmp(edge a,edge b){
    	return a.cost < b.cost;
    }
    
    int Kruskal(){
    	init_union_find_set();
    	sort(E,E+m,cmp);
    	int ret = 0;
    	for(int i = 0 ; i < m ; i++){
    		if( !same(E[i].from , E[i].to)){
    			union_set(E[i].from,E[i].to);
    			ret += E[i].cost;
    		}
    	}
    	int cnt = 0;
    	for(int i = 1 ; i <= n ; i++){	if( par[i] == i )	cnt++;   }
    	if( cnt > 1 )	ret = 1;
    	return ret;
    }
    int main(){
    	int from , to , cost;
    	while(~scanf("%d%d",&n,&m)){
    		for(int i = 0 ; i < m ; i++){
    			scanf("%d%d%d",&from,&to,&cost);
    			E[i].from = from , E[i].to = to , E[i].cost = -cost;
    		}
    		int ret = Kruskal();
    		printf("%d
    ",-ret);
    	}
    	return 0;
    }
  • 相关阅读:
    Maven安装
    Linux登录欢迎图案
    GC的性能指标和内存容量配置原则
    java堆结构和垃圾回收
    框架设计知识点纵览(笔记)
    .net core在Linux本地化Localization的一次填坑
    .Net Identity OAuth 2.0 SecurityStamp 使用
    CentOS 7 安装. Net Core SDK 2.0
    Docker基本命令与使用 —— Docker容器的网络连接(四)
    Docker基本命令与使用 —— Dockerfile指令与构建(三)
  • 原文地址:https://www.cnblogs.com/WArobot/p/7050060.html
Copyright © 2020-2023  润新知