zoukankan      html  css  js  c++  java
  • Slim Span UVA

    题意:寻找满足条件的最小生成树,条件是生成树中最长边与最短边的差越小越好。

    题解:将边进行排序后,枚举第一条边,然后不断更新答案就行了。

     1 #define INF 1e8
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<iostream>
     5 #include<algorithm>
     6 using namespace std;
     7 
     8 const int maxn=10005;
     9 
    10 struct edge{
    11     int u,v,cost;
    12     bool operator<(const edge& i)const{
    13         return cost<i.cost;
    14     }
    15 }es[maxn];
    16 
    17 int n,m,cnt;
    18 int F[105];
    19 
    20 void Init(){
    21     for(int i=1;i<=n;i++) F[i]=i;
    22     cnt=1;
    23 }
    24 
    25 int Find(int a){
    26     if(a!=F[a]) F[a]=Find(F[a]);
    27     return F[a];
    28 }
    29 
    30 bool unite(int a,int b){
    31     int x=Find(a),y=Find(b);
    32     if(x==y) return false;
    33     else { F[x]=y; return true; } 
    34 }
    35 
    36 int Kruskal(){
    37     sort(es,es+m);
    38     int ans=INF;
    39     for(int i=0;i<m;i++){
    40         Init();
    41         unite(es[i].u,es[i].v);
    42         for(int j=i+1;j<m;j++){ 
    43             if(unite(es[j].u,es[j].v)){
    44                 cnt++;
    45                 if(cnt==n-1) ans=min(ans,es[j].cost-es[i].cost);
    46             }
    47         }
    48     }
    49     return ans;
    50 }
    51 
    52 int main()
    53 {   while(~scanf("%d%d",&n,&m)){
    54         if(n==0&&m==0) break;
    55         for(int i=0;i<m;i++) scanf("%d%d%d",&es[i].u,&es[i].v,&es[i].cost);
    56         int ans=Kruskal(); 
    57         if(m==0||(n>2&&m==1)) cout<<"-1"<<endl;
    58         else if(n==2&&m==1) cout<<"0"<<endl;
    59         else if(ans==INF) cout<<"-1"<<endl;
    60         else cout<<ans<<endl;
    61     }
    62     return 0;
    63 }
  • 相关阅读:
    解决百度网盘倍速需要会员问题
    npm run dev其实就是vue-cli-service serve
    git常见操作和git原理
    ajax promise三种状态
    ajax get请求
    vue2.0x methods中一个函数调用另外一个函数
    Web前端开发规范之文件存储位置规范
    大数据应用期末总评
    分布式文件系统HDFS 练习
    安装Hadoop
  • 原文地址:https://www.cnblogs.com/zgglj-com/p/7351368.html
Copyright © 2011-2022 走看看