AOJ 2224 Save your cats( 最小生成树 )


链接:传送门

题意:有个女巫把猫全部抓走放在一个由 n 个木桩(xi,yi),m 个篱笆(起点终点木桩的编号)围成的法术领域内,我们必须用圣水才能将篱笆打开,然而圣水非常贵,所以我们尽量想降低花费来解救所有的猫

思路:这张图的生成树相当于这个领域的“框架”,总的周长是一定的,只需要让“框架”最长那么其他篱笆(解救猫咪“开口”的地方)也就最短,只需要把边权处理成负数然后做最小生成树,最后 周长 + 最小生成树的路径长 即为答案


/*************************************************************************
    > File Name: aoj2224.cpp
    > Author:    WArobot 
    > Blog:      http://www.cnblogs.com/WArobot/ 
    > Created Time: 2017年06月19日 星期一 19时52分17秒
 ************************************************************************/

#include<bits/stdc++.h>
using namespace std;

const int MAX_N = 10010;
const int MAX_M = 200000;
struct point{
    int x, y;
}P[MAX_N];
struct edge{
    int from , to;
    double cost;
}E[MAX_M];

int n , m;
int par[MAX_N];

void init_union_find_set()  { for(int i = 0 ; i <= 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;
}
double Kruskal(){
    init_union_find_set();
    sort(E,E+m,cmp);
    double 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;
        }
    }
    return ret;
}

double Distence(point a,point b){
    return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
}

int main(){
    int from , to;
    double cost , sum;
    while(~scanf("%d%d",&n,&m)){
        sum = 0;
        for(int i = 1 ; i <= n ; i++){
            scanf("%d%d",&P[i].x,&P[i].y);
        }
        for(int i = 0 ; i < m ; i++){
            scanf("%d%d",&E[i].from , &E[i].to);
            E[i].cost = Distence( P[E[i].from] , P[E[i].to] ) * -1;
            sum += ( E[i].cost * -1 );
        }
        double ret = Kruskal();
        printf("%.3lf\n",sum + ret);
    }
    return 0;
}

转载于:https://www.cnblogs.com/WArobot/p/7050398.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值