Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ competitive programming mst

#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++ check first character of string 
Cpp :: C++ convert vector of digits into integer 
Cpp :: c++ code for insertion sort 
Cpp :: how to check is some number is divisible by 3 in c++ 
Cpp :: qt popup window 
Cpp :: min vector c++ 
Cpp :: how to use string variable in switch case in c++ 
Cpp :: count occurrences of character in string c++ 
Cpp :: c++ loop through string 
Cpp :: c++ measure time in microseconds 
Cpp :: character array to string c++ stl 
Cpp :: max of two elements c++ 
Cpp :: array and for loop in c++ 
Cpp :: how to get length of a file in c++ 
Cpp :: string to vector char c++ 
Cpp :: Heap pinter c++ 
Cpp :: c++ int main() 
Cpp :: cpp binary tree 
Cpp :: cpp multidimensional vector 
Cpp :: how to iterate throguh a string in c++ 
Cpp :: what does the modularity mean in c++ 
Cpp :: how to rotate canvas android 
Cpp :: size of pointer array 
Cpp :: C++ String Copy Example 
Cpp :: uses of gamma rays 
Cpp :: for loop c++ 
Cpp :: cpp string slice 
Cpp :: how to read files in c++ 
Cpp :: how to specify the number of decimal places in c++ 
Cpp :: vector to string cpp 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =