Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ mst kruskal

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

#define ll long long
#define llu unsigned llu
#define F first
#define S second

typedef pair<int,int> ii;
typedef pair<int,ii> iii;
typedef vector<int> vi;
vector <iii> g;
vi par;

int fnd(int x){
    if (x == par[x])
        return x;
    par[x] = fnd(par[x]);
    return par[x];
}

void onion(int a, int b){
    par[fnd(a)] = par[fnd(b)];
}

int main() {
    int n, m=0;
    cin>>n;
    
    int i, ans = 0;
    for (i = 0; i<n; i++)
        par.push_back(i);
    
    int a,b,w;
    while( cin>>a>>b>>w ){
        m++;
        g.push_back(iii(w, ii(a,b)));
    }
    sort(g.begin(), g.end());
            
    for(i = 0; i<m; i++){
        if (fnd(g[i].S.F) != fnd(g[i].S.S)){
            ans += g[i].F;
            onion(g[i].S.F, g[i].S.S);
        }
    }
                    
    cout<<ans<<endl;
                    
    return 0;
}

/*
Sample Input:
6
0 1 1
0 3 5
1 3 7
1 2 6
2 5 8
2 4 3
3 4 6
4 5 9

Sample Output:
23
*/
Comment

PREVIOUS NEXT
Code Example
Cpp :: minimum spanning trees c++ 
Cpp :: cpp map iterate over keys 
Cpp :: how to make for loop in c++ 
Cpp :: check if an element is in a map c++ 
Cpp :: min element c++ 
Cpp :: g++ optimization flags 
Cpp :: if even number c++ 
Cpp :: how to check if a value is inside an array in c++ 
Cpp :: qt disable resizing window 
Cpp :: change abstract title name latex 
Cpp :: gfgdf 
Cpp :: latex double subscript 
Cpp :: factorial in c++ 
Cpp :: c++ struct with default values 
Cpp :: convert all characters in string to uppercase c++ 
Cpp :: c++ iterate map 
Cpp :: how to make a list in c++ 
Cpp :: min heap and max heap using priority queue 
Cpp :: cpp init multidimensional vector 
Cpp :: vector search by element 
Cpp :: c++ greatest common divisor 
Cpp :: c++ colored output 
Cpp :: hamming distance c++ 
Cpp :: c++ friend class 
Cpp :: c++ string to char array 
Cpp :: print a string with printf in c++ 
Cpp :: sort a vector c++ 
Cpp :: How to create files in C++ 
Cpp :: pointer in return function c++ 
Cpp :: arduino xor checksum 
ADD CONTENT
Topic
Content
Source link
Name
4+1 =