zoukankan      html  css  js  c++  java
  • EOJ2529 强大的lwc

    http://acm.cs.ecnu.edu.cn/problem.php?problemid=2529

    题意,求修造为通路耗费的最小精力。

    即求无向图的最小生成树,此题注意结点是0到n 为n+1个,判断连通条件可以判断树的边数是不是为n,此题用prim

     1 #include<map>
     2 #include<cmath>
     3 #include<cctype>
     4 #include<cstdio>
     5 #include<string>
     6 #include<cstdlib>
     7 #include<cstring>
     8 #include<iostream>
     9 #include<algorithm>
    10 using namespace std;
    11 const int inf=999999999;
    12 int mat[105][105];
    13 int n;
    14 void init(){
    15     for(int i=0;i<=n;i++)
    16         for(int j=0;j<=n;j++)
    17             mat[i][j]=inf;
    18 }
    19 int prim(){                                  //注意 ,都是从0-n
    20     int lowcost[105],s[105];
    21     int ans=0,cnt=0;
    22     for(int i=0;i<=n;i++){
    23         lowcost[i]=mat[0][i];
    24         s[i]=0;
    25     }
    26     s[0]=1;
    27     for(int i=0;i<=n;i++){
    28         int min=inf,k;
    29         for(int j=0;j<=n;j++)
    30             if(!s[j] && lowcost[j]<min){
    31                 min=lowcost[j];
    32                 k=j;
    33             }
    34         if(min==inf) break;
    35         ans+=min;
    36         cnt++;
    37         s[k]=1;
    38         for(int j=0;j<=n;j++)
    39             if(!s[j] && mat[k][j]<lowcost[j])
    40                 lowcost[j]=mat[k][j];
    41     }
    42     if(cnt==n)           //判断是否连通
    43         return ans;
    44     else return 0;
    45 }
    46 int main(){
    47     int t;
    48     cin>>t;
    49     while(t--){
    50         int m;
    51         scanf("%d%d",&n,&m);
    52         init();
    53         while(m--){
    54             int a,b,c;
    55             scanf("%d%d%d",&a,&b,&c);
    56             if(c<mat[a][b])
    57                 mat[a][b]=mat[b][a]=c; //注意是无向
    58         }
    59         /*for(int i=0;i<=n;i++){
    60             for(int j=0;j<=n;j++)
    61                 printf("%d ",mat[i][j]);
    62             cout<<endl;
    63         }*/
    64         int ans=prim();
    65         if(ans)printf("%d\n",ans);
    66         else printf("-1\n");
    67     }
    68     return 0;
    69 }                                                                                
    View Code
  • 相关阅读:
    禁止后台运行
    图标的圆角和光晕效果和启动画面
    IOS 开发 有关iPhone程序的安装目录UUID 唯一标识
    NSOperation与performSelectorOnMainThread
    Java web开发学习规划
    JAVA类集
    java 四种xml操作方式的基本使用方法
    用JDOM操作XML文件
    java web 学习
    过去的,将来的
  • 原文地址:https://www.cnblogs.com/KimKyeYu/p/3132400.html
Copyright © 2011-2022 走看看