zoukankan      html  css  js  c++  java
  • UVA 1395 Slim Span 最小生成树

    UVA 1395     Slim Span

     先上代码,日后写题解

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #define inf 1e8
    #define maxn 10005
    using namespace std;
    
    struct edge{
    int to,from,cost;
    }s[maxn];
    
    bool cmp(const edge a,const edge b){
        return a.cost < b.cost;
    }
    
    int par[maxn],n,m;
    
    void init(){
         for(int i = 1; i <= m; i++)
            par[i] = i;
    }
    int finds(int x){
        if (par[x] == x) return x;
        else return par[x] =finds(par[x]);
    }
    void unite(int x,int y){
        x=finds(x),y=finds(y);
        if(x==y) return ;
        par[x]=y;
    }
    bool same(int x,int y){
        if(finds(x) == finds(y)) return true;
        return false;
    }
    
    
    int kruskal(int x){
        int cnt = 0, l = inf, r = -inf;
        init();
        for(int i = x; i < n; i++){
            edge e = s[i];
            if(!same(e.to,e.from)) {
               unite(e.to,e.from);
               cnt++;
               r = max(r,e.cost);
               l = min(l,e.cost);
               if(cnt == m-1) return r-l;
            }
        }
        return -1;
    }
    void slove(){
        sort(s,s+n,cmp);
        int res = inf,flag=-1;
        for(int i = 0; i < n; i++){
            int op =kruskal(i);
            if(op!=-1 && op < res){
                res = op;
                flag = 1;
            }
        }
        if(flag == -1) printf("-1
    ");
            else printf("%d
    ", res);
    }
    int main(){
       //freopen("data.in.txt","r",stdin);
        while(scanf("%d%d", &m, &n) && (n||m)){
            for(int i = 0; i < n; i++)
                scanf("%d%d%d", &s[i].from, &s[i].to, &s[i].cost);
              slove();
    
        }
    
        return 0;
    }
    View Code
  • 相关阅读:
    TOMCAT热部署 catalina.home catalina.base
    spring boot test MockBean
    源码分析ConcurrentHashMap
    源码分析Thread
    源码分析String
    jvm 占用高的问题定位
    docker 资源限制
    数据库设计方案与优化
    linux搜索查找类命令|--grep指令
    linux搜索查找类命令|--locate命令
  • 原文地址:https://www.cnblogs.com/cshg/p/5678846.html
Copyright © 2011-2022 走看看