Search
 
SCRIPT & CODE EXAMPLE
 

CPP

minimum spanning trees 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

PREVIOUS NEXT
Code Example
Cpp :: c++ product of vector 
Cpp :: c++ rand 
Cpp :: online cpp to exe converter 
Cpp :: apply pca to dataframe 
Cpp :: c++ check if string is empty 
Cpp :: C++ convert integer to digits, as vector 
Cpp :: c++ declaring and initializing strings 
Cpp :: remove last character from string c++ 
Cpp :: string reversal 
Cpp :: how to open and read text files in c++ 
Cpp :: roscpp publish int32 
Cpp :: cpp case 
Cpp :: how to make a random number in c++ 
Cpp :: scan line in c++ 
Cpp :: string reverse stl 
Cpp :: c++ check if vector is sorted 
Cpp :: C++ Swap 2 Variables Without Using 3rd Variable 
Cpp :: nth node from end of linked list 
Cpp :: memset in c++ 
Cpp :: string iterator in c++ 
Cpp :: docker.io : Depends: containerd (= 1.2.6-0ubuntu1~) E: Unable to correct problems, you have held broken packages 
Cpp :: cpp cin 
Cpp :: combine two vectors c++ 
Cpp :: c++ structure 
Cpp :: string to uint64_t c++ 
Cpp :: stringstream stream number to string 
Cpp :: find duplicate from an array c++ 
Cpp :: reverse order binary tree in c++ 
Cpp :: how to square a number in c++ 
Cpp :: What is the "--" operator in C/C++? 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =