• 继续畅通工程


    省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。 

    Input测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。 

    当N为0时输入结束。Output每个测试用例的输出占一行,输出全省畅通需要的最低成本。Sample Input

    3
    1 2 1 0
    1 3 2 0
    2 3 4 0
    3
    1 2 1 0
    1 3 2 0
    2 3 4 1
    3
    1 2 1 0
    1 3 2 1
    2 3 4 1
    0

    Sample Output

    3
    1
    0
    解题思路:最小生成树的问题:
     1 #include<iostream>
     2 #include <string.h>
     3 #include <stdio.h>
     4 #include <queue>
     5 
     6 using namespace std;
     7 
     8 const int MAX = 10000 + 500;
     9 const long long  MAX1 = 1e10;
    10 
    11 int visit[MAX];
    12 struct S
    13 {
    14     int x,y,len,ok;
    15 };
    16 S Map;
    17 
    18 struct cmp
    19 {
    20     bool operator() (S a,S b)
    21     {
    22         return a.len > b.len;
    23     }
    24 };
    25 
    26 int Find(int x)
    27 {
    28     if(x == visit[x])
    29         return x;
    30     else
    31         return visit[x] = Find(visit[x]);
    32 }
    33 
    34 int B(int x,int y)
    35 {
    36     int tt=0;
    37     int Tx =Find(x);
    38     int Ty = Find(y);
    39     if(Tx != Ty)
    40     {
    41         visit[Tx]= Ty;
    42         tt=1;
    43     }
    44     return tt;
    45 }
    46 
    47 int N;
    48 
    49 int main()
    50 {
    51     while(cin>>N&&N)
    52     {
    53         for(int i =1;i<=N;i++)
    54             visit[i] = i;
    55         long long sum =0;
    56         priority_queue<S,vector<S>,cmp>p;
    57         for(int i =1;i <= N*(N-1)/2;i++)
    58         {
    59             scanf("%d %d %d %d",&Map.x,&Map.y,&Map.len,&Map.ok);
    60             if(Map.ok==1)
    61             {
    62                B(Map.x,Map.y);
    63             }
    64             else
    65                 p.push(Map);
    66         }
    67         while(!p.empty())
    68         {
    69             Map = p.top();
    70             p.pop();
    71             if(B(Map.x,Map.y)==1)
    72             {
    73                 if(Map.ok==0)
    74                     sum+=Map.len;
    75             }
    76         }
    77         cout<<sum<<endl;
    78 
    79     }
    80 
    81     return 0;
    82 }


  • 相关阅读:
    关于工作习惯的一点思考
    BulkSqlCopy 批量导入数据(Ef支持)
    记录下最近项目中常用到的SQL语句
    对象化前端表单(Form)提交
    Python描述符 (descriptor) 详解
    Python装饰器之 property()
    Python魔法方法之属性访问 ( __getattr__, __getattribute__, __setattr__, __delattr__ )
    Python魔法方法总结及注意事项
    面向对象编程(二)
    面向对象编程(一)
  • 原文地址:https://www.cnblogs.com/a2985812043/p/7375381.html
Copyright © 2020-2023  润新知