Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ kruskal algorithm

#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

Kruskal algorithm in c++

Kruskal MST 
Comment

PREVIOUS NEXT
Code Example
Cpp :: what is the difference between i++ and ++ i ? 
Cpp :: capitalize first letter c++ 
Cpp :: optimized bubble sort 
Cpp :: Unsorted Linked list in c++ 
Cpp :: what is the short cut way to find the max and min element in an array in c++ 
Cpp :: taking a vector in c++ containing element 
Cpp :: c++ switch string 
Cpp :: c++ swapping two numbers 
Cpp :: conditional operator in cpp 
Cpp :: c++ length of char* 
Cpp :: random number in a range c++ 
Cpp :: C++ switch - case - break 
Cpp :: how to use decrement operator in c++ 
Cpp :: map in c++ sorted descending order 
Cpp :: for loop with array c++ 
Cpp :: singleton c++ 
Cpp :: int to string c++ 
Cpp :: opencv c++ image write 
Cpp :: c++ simple projects 
Cpp :: string to decimal c++ strtol 
Cpp :: Parenthesis Checker using stack in c++ 
Cpp :: c vs c++ 
Cpp :: remove decimal c++ 
Cpp :: how to find 2d vector length cpp 
Cpp :: c++ string element access 
Cpp :: cudamemcpy 
Cpp :: To Lower Case leetcode solution in c++ 
Cpp :: reverse level order traversal 
Cpp :: bee 1002 solution 
Cpp :: array to string c++ 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =