zoukankan      html  css  js  c++  java
  • HDU 5253 最小生成树(kruskal)+ 并查集

    题目链接


    #include<cstdio>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #define N 1000010
    using namespace std;
    struct node
    {
        int a;//端点1
        int b;//端点2
        int num;//权值
    };
    bool cmp(node x,node y)//按权值升序
    {
        return x.num<y.num;
    }
    int maps[1003][1003];
    node edge[N*2];//边数=2mn-m-n<2mn
    int father[N];
    int r[N];
    int finds(int x)
    {
        if(father[x]!=x)
        father[x]=finds(father[x]);
        return father[x];
    }
    void connect(int a,int b)
    {
        if(r[a]>r[b])
        father[b]=a;
        else if(r[a]<r[b])
        father[a]=b;
        else
        {
            father[a]=b;
            r[b]++;
        }
    }
    int main()
    {
        int T,cas=1,n,m,ans,id;
        int i,j;
        scanf("%d",&T);
        while(T--)
        {
            int numedge=0;//边数
            ans=0;
            memset(r,0,sizeof(r));
            scanf("%d%d",&n,&m);
            for(i=1;i<=n;i++)
            {
                for(j=1;j<=m;j++)
                scanf("%d",&maps[i][j]);
            }
            for(i=1;i<=n;i++)
            {
                for(j=1;j<=m;j++)
                {
                    id=(i-1)*m+j;
                    father[id]=id;
                    if(i<n)//除最后一行外
                    {
                        numedge++;
                        edge[numedge].a=id;
                        edge[numedge].b=i*m+j;
                        edge[numedge].num=abs(maps[i][j]-maps[i+1][j]);
                    }
                    if(j<m)//除最后一列外
                    {
                        numedge++;
                        edge[numedge].a=id;
                        edge[numedge].b=(i-1)*m+j+1;
                        edge[numedge].num=abs(maps[i][j]-maps[i][j+1]);
                    }
                }
            }
            sort(edge+1,edge+numedge+1,cmp);//权值排序
            for(i=1;i<=numedge;i++)
            {
                int x=finds(edge[i].a);
                int y=finds(edge[i].b);
                if(x!=y)
                {
                    connect(x,y);
                    ans+=edge[i].num;
                }
            }
            printf("Case #%d:
    %d
    ",cas++,ans);
        }
        return 0;
    }
    


  • 相关阅读:
    JS函数浅析(一)
    H5_canvas与svg
    h5+js视频播放器控件
    【BZOJ3622】已经没有什么好害怕的了
    【9.29 模拟】T3 小清新最优化(easy)
    9.27模拟
    9.26 模拟
    4062 -- 【清华集训2012】串珠子
    【SNOI2017】炸弹
    P3216 [HNOI2011]数学作业
  • 原文地址:https://www.cnblogs.com/westwind1005/p/5975231.html
Copyright © 2011-2022 走看看