zoukankan      html  css  js  c++  java
  • HDU-1102-Constructing Roads(并查集)

    题目链接

    http://acm.hdu.edu.cn/showproblem.php?pid=1102

    这题大意就不讲了,

    这题很容易,不过我做的很不爽,一个下午,一直WA,后来才发现数组开小了

    只开了s[6000],本来100*100=10000,要开至少10000的搞糊了,一直WA

    一个下午,以后做题,要把思路全部理清才开始敲代码,别边想边敲,那样,很容易搞错

    我的代码

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<algorithm>
    using namespace std;

    struct node
    {
    int x,y,d;
    }s[10005];

    int father[111];
    int sum;

    bool cmp(const node &a,const node &b)
    {
    return a.d<b.d;
    }

    int Find(int x)
    {
    if(x==father[x]) return x;
    father[x]=Find(father[x]);
    return father[x];
    }

    void Union(int x,int y,int d)
    {
    x=Find(x);
    y=Find(y);
    if(x!=y)
    {
    father[x]=y;
    sum=sum+d;
    }
    }

    int main(void)
    {
    int n,m,i,j,k,l;
    while(scanf("%d",&n)==1)
    {
    l=0;
    for(i=1;i<=n;i++)
    {
    for(j=1;j<=n;j++)
    {
    s[l].x=i;
    s[l].y=j;
    scanf("%d",&s[l].d);
    l++;
    }
    }
    int q,x,y;
    scanf("%d",&q);
    for(i=1;i<=q;i++)
    {
    scanf("%d%d",&x,&y);
    s[(x-1)*n+y-1].d=0;
    s[(y-1)*n+x-1].d=0;
    }
    sort(s,s+l,cmp);
    for(i=1;i<=n;i++)
    father[i]=i;
    sum=0;
    for(i=0;i<l;i++)
    {
    Union(s[i].x,s[i].y,s[i].d);
    }
    k=0;
    for(i=0;i<=n;i++)
    {
    if(i==father[i])
    k++;
    }
    if(k)
    printf("%d ",sum);
    }
    return 0;
    }

  • 相关阅读:
    MySQL学习笔记
    FileInputStream
    Java 多个if 和多个else if 的区别
    Flume 聚合
    Flume SinkProcessor
    Flume ChannelSelector (包括自定义flume拦截器)
    Flume 案例演示
    為政第二
    各种版本 WordCount
    學而第一
  • 原文地址:https://www.cnblogs.com/liudehao/p/3940339.html
Copyright © 2011-2022 走看看