码迷,mamicode.com
首页 > 其他好文 > 详细

kruskal

时间:2020-06-14 23:20:59      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:题目   out   name   ble   problem   ret   tps   int   clu   

题目:https://pintia.cn/problem-sets/15/problems/718

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std ;

struct mat{
    int a,b,c;
};

int father[1010] ;
int N , M ;
vector<mat> v ;

bool cmp( mat a, mat b){
    return a.c<b.c ;
    }

int findFather(int x){
        return x == father[x] ? x : x = findFather(father[x]) ;
    }

int main(){
    cin>>N>>M;
    for(int i = 0 ; i < M ; ++ i) {
        int a,b,c ;
        cin>>a>>b>>c ;
        v.push_back({a,b,c});
    }
    
    sort(v.begin() , v.end() ,cmp) ;
    int cost = 0 ;
    int edges = 0 ;
    
    for(int i = 0 ; i < N ; ++ i) father[i]  =  i ;
    
    for( auto &x : v){
        int fa = findFather(x.a) , fb = findFather(x.b) ;  
        //kruskal
        if( fa != fb ){
             father[fa] = fb ;
            cost += x.c ;
            edges ++ ;
        }
    }
    if(edges == N - 1) cout<< cost <<endl;
    else cout<< -1 <<endl;
   
    return  0 ;
}

题目:https://pintia.cn/problem-sets/15/problems/897

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

const int N = 110 ;

struct mat{
    int a,b,cost,d;
    
    bool operator < (const mat a)const{
        return cost < a.cost;
    }
};

vector<mat> v ;
int cost = 0 ;
int root[N] ;

int findRoot(int x){
    return x == root[x] ? x : x = findRoot(root[x]) ;
    }

int kruskal(){
    for(auto x : v){
        int roota = findRoot(x.a) ,rootb = findRoot(x.b);
        if(roota != rootb){
            root[rootb] = roota;    
            cost += x.cost ;
        }
    }
    
    return cost ;
}

int main(){
    for(int i = 0 ; i < N ; ++ i) root[i] = i ;
    
    int n ,len;
    cin >> n ;
    len = n * (n - 1) / 2 ;
    
    int a,b,c,d;
    for(int i = 0 ;i < len ; i++)
    {
        cin>>a>>b>>c>>d;
        v.push_back({a,b,c,d});
        if(d == 1){
            int roota = findRoot(a) , rootb = findRoot(b);
            if(roota != rootb){
                root[rootb] = roota;
            }
        }
    }
    sort(v.begin() , v.end()) ;
    cout<<kruskal()<<endl;
    
    
    return 0;
}

kruskal

标签:题目   out   name   ble   problem   ret   tps   int   clu   

原文地址:https://www.cnblogs.com/lkfsblogs/p/13127550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!