zoukankan      html  css  js  c++  java
  • 1863 畅通工程-并查集最小生成树

    题目链接

    问题描述:

      

    简单的最小生成树的题,将路径按cost从小到大排序,利用克鲁斯塔尔求最小生成树算法就行。

    代码:

      

     1 #include<iostream>
     2 #include<queue>
     3 #include<algorithm>
     4 
     5 using namespace std;
     6 struct  Road
     7 {
     8     int beg;
     9     int end;
    10     int cost;
    11     Road(int beg, int end, int cost)
    12     {
    13         this->beg = beg;
    14         this->end = end;
    15         this->cost = cost;
    16     }
    17     bool operator <(const Road& b) const 
    18     //必须要带const,使用STL,或者自己写compare函数
    19     //优先级大的在队列的前面,所以重载的时候需要注意需要的形式
    20     {
    21         return (cost > b.cost);
    22     }
    23     
    24 };
    25 
    26 int father[101];
    27 int getfather(int a) //路径压缩
    28 {
    29     if(father[a] != a)
    30     {
    31             father[a] = getfather(father[a]);
    32         return father[a];
    33     }
    34     else
    35         return father[a];
    36 }
    37 
    38 priority_queue<Road> q;
    39 //并查集
    40 
    41 int num;
    42 int vnum;
    43 
    44 int main()
    45 {
    46     cin>>num>>vnum;
    47     int scost = 0;
    48     int  ok = 0;
    49     Road a = {0,0,0};
    50     while(num)
    51     {
    52         scost = 0;
    53         for(int i=0; i<=vnum; i++)
    54         {
    55             father[i] = i;
    56         }
    57         for(int i=0; i<num; i++)
    58         {
    59             cin>>a.beg>>a.end>>a.cost;
    60             q.push(a);
    61         }
    62         while(!q.empty())
    63         {
    64             a = q.top();
    65             q.pop();
    66             if(getfather(a.beg) != getfather(a.end))
    67             {
    68                 father[a.end] = father[a.beg];
    69                 scost += a.cost;
    70                 ok++;
    71             }
    72         }
    73         if(ok == vnum-1)
    74             cout<<scost<<endl;
    75         else
    76             cout<<"?"<<endl;
    77         ok = 0;
    78         cin>>num>>vnum;
    79 
    80     }
    81     return 0;
    82 }
  • 相关阅读:
    注册系统
    android登录界面
    android作业 购物界面
    第六周jsp作业
    JSP第四周
    JSP第二次作业
    JSP第一次作业
    第一周软件测试
    第九次安卓
    购物菜单
  • 原文地址:https://www.cnblogs.com/Crossea/p/11746940.html
Copyright © 2011-2022 走看看