zoukankan      html  css  js  c++  java
  • HDU 1879 继续畅通工程

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=1879


    并查集+优先队列...用cin会超时...TLE了好几次


    #include <iostream>
    #include<queue>
    #include<cstdio>
    #define MAX_N 105
    using namespace std;
    class rode
    {
    public:
        int from;
        int to;
        int cost;
        int sign;
    };
    
    int par[MAX_N];
    int high[MAX_N];
    int c;          //记录当前有几个集合
    bool operator <(rode a,rode b)
    {
        return a.cost>b.cost;
    }
    priority_queue <rode> data;
    void init(int n)        //初始化
    {
        c=n;
        for(int i=1;i<=n;i++)
        {
            par[i]=i;
            high[i]=0;
        }
    }
    int ifind(int x)
    {
        if(par[x]==x)
            return x;
        else
            return par[x]=ifind(par[x]);
    }
    void unite(int x,int y)
    {
        x=ifind(x);
        y=ifind(y);
        if(x==y)
            return;
        if(high[x]<high[y])
            par[x]=y;
        else
        {
             par[y]=x;
             if(high[x]==high[y])
                high[x]++;
        }
        c--;
    
    }
    bool same (int x,int y)
    {
        return ifind(x)==ifind(y);
    }
    void readrode(int n)
    {
        rode t;
        while(!data.empty())
            data.pop();
    
        for(int i=0; i<n*(n-1)/2; i++)
        {
            scanf("%d%d%d%d",&t.from,&t.to,&t.cost,&t.sign);
            if(t.sign)      //如果路已修好
                unite(t.from,t.to);
            else            //未修好,则加入队列
                data.push(t);
        }
    }
    int markrode(void)
    {
        int sum=0;
        rode t;
        while(!data.empty()&&c>1)
        {
            t=data.top();
            data.pop();
            if(!same(t.from,t.to))
            {
                unite(t.from,t.to);
                sum+=t.cost;
            }
    
        }
        return sum;
    
    }
    
    int main()
    {
        int n;
        while(scanf("%d",&n)&&n)
        {
            init(n);
            readrode(n);
            cout<<markrode()<<endl;
    
        }
    
        return 0;
    }
    


  • 相关阅读:
    宽带手记
    adb的logcat使用
    项目经理
    小A老空调需求管理小记
    作为一个项目经理你关注的是什么
    技术采撷
    项目的落地目标
    和我一起使用postcss+gulp进行vw单位的移动端的适配
    高级程序设计第十三章,简单的事件捕获事件冒泡整理
    javascript高级程序设计第二章知识点提炼
  • 原文地址:https://www.cnblogs.com/frankM/p/4399494.html
Copyright © 2011-2022 走看看