Search
 
SCRIPT & CODE EXAMPLE
 

CPP

kruskal in c++

#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 :: how to run a c++ program in the background 
Cpp :: how to read wav file in C++ 
Cpp :: c++ lock 
Cpp :: create random vectors c++ 
Cpp :: Could not load the Visual C++ component "VCBuild.exe". To fix this, 1) install the .NET Framework 2.0 SDK, 2) install Microsoft Visual Studio 2005 or 3) add the location of the component to the system path if it is installed elsewhere. 
Cpp :: find in set of pairs using first value cpp 
Cpp :: switch case with string c++ 
Cpp :: counting sort c++ 
Cpp :: convert int to enum c++ 
Cpp :: c++ open file 
Cpp :: syntax c++ 
Cpp :: c++ case 
Cpp :: time function c++ 
Cpp :: sin in c++ 
Cpp :: latex table landscape 
Cpp :: insert vector to end of vector c++ 
Cpp :: do while loop c++ loops continuously 
Cpp :: c++ typeid 
Cpp :: c++ initialize multidimensional vector 
Cpp :: push_back struct c++ 
Cpp :: splice string in c++ 
Cpp :: vector size for loop 
Cpp :: divide and conquer based algorithm to find maximum and minimum of an array 
Cpp :: how to get size of 2d vector in c++ 
Cpp :: indexing strings in c++ 
Cpp :: c++ code for bubble sort 
Cpp :: what is thread in c++ 
Cpp :: cpp create lambda with recursion 
Cpp :: factorial loop c++ 
Cpp :: c++ get the line which call a function 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =