kruskal
作者:互联网
题目: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;
}
标签:int,kruskal,roota,rootb,cost,findRoot,include 来源: https://www.cnblogs.com/lkfsblogs/p/13127550.html