Aizu-2224Save your cats并查集+最小生成树

Posted ckxkexing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Aizu-2224Save your cats并查集+最小生成树相关的知识,希望对你有一定的参考价值。

Save your cats

题意:存在n个点,有m条边( input中读入的是 边的端点,要先转化为边的长度 ),做一个最小生成树,使得要去除的边的长度总和最小;

思路:利用并查集和求最小生成树的方法,注意这里的排序要从大到小排,这样最后建树的消耗最大,反过来去除的最小;

当然题意不是这么直白,感觉以后看到要做一个不成环的图时,要想到最小生成树;

下面是ac代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
const int maxn =10007;
const int mx   =2e6+7;
using namespace std;
int n,m,fa[maxn];
struct node {
    int from;
    int to;
    double r;
}a[mx];
struct nn{
    int x,y;
}p[maxn];

bool cmp(node a,node b)
{
    return a.r>b.r;                    //这里的判断用大于,使得sort从大到小排列
}
void init(){
    for(int i=1;i<=n;i++)
        fa[i] = i;
    memset(a,0,sizeof(a));
    memset(p,0,sizeof(p));
}
int find(int x)
{
    if(fa[x]==x)return x;
    else return fa[x] = find (fa[x]);
}
bool uni(int x,int y)
{
    int px = find(x);
    int py = find (y);
    if(px==py)return false;
    fa[px] = py;
    return true;
}
int main(){
    scanf("%d%d",&n,&m);
    init();
    for(int i=1;i<=n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        p[i].x=x;
        p[i].y=y;
    }
    double sum = 0,res=0;
    for(int i=1;i<=m;i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        double tmp = sqrt((p[u].x-p[v].x)*(p[u].x-p[v].x)+(p[u].y-p[v].y)*(p[u].y-p[v].y));
        a[i].from=u;
        a[i].to=v;
        a[i].r = tmp;
        sum+=tmp;
    }
    sort(a+1,a+1+m,cmp);
    for(int i=1;i<=m;i++)
    {
        int u = a[i].from;
        int v = a[i].to;
        if(uni(u,v))res+=a[i].r;
    }
    printf("%.3lf\n",sum-res);
    return 0;
}

 

以上是关于Aizu-2224Save your cats并查集+最小生成树的主要内容,如果未能解决你的问题,请参考以下文章

Aizu2224 Save your catsKruscal算法+最大生成树

AOJ 2224 Save your cats (Kruskal)

Summary: curated List of Top 75 LeetCode Questions to Save Your Time

Finding Your Raspberry Pi’s System Information

Save Money for Your Company 最小矩形覆盖(非计算几何)/找出N条直线相交点的边缘点/ find the dominating points of N lines

Save Money for Your Company 最小矩形覆盖(非计算几何)/找出N条直线相交点的边缘点/ find the dominating points of N lines