Search
 
SCRIPT & CODE EXAMPLE
 

CPP

find the graph is minimal spanig tree or not

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>

using namespace std;
const int MAX = 1e4 + 5;
int id[MAX], nodes, edges;
pair <long long, pair<int, int> > p[MAX];

void initialize()
{
    for(int i = 0;i < MAX;++i)
        id[i] = i;
}

int root(int x)
{
    while(id[x] != x)
    {
        id[x] = id[id[x]];
        x = id[x];
    }
    return x;
}

void union1(int x, int y)
{
    int p = root(x);
    int q = root(y);
    id[p] = id[q];
}

long long kruskal(pair<long long, pair<int, int> > p[])
{
    int x, y;
    long long cost, minimumCost = 0;
    for(int i = 0;i < edges;++i)
    {
        // Selecting edges one by one in increasing order from the beginning
        x = p[i].second.first;
        y = p[i].second.second;
        cost = p[i].first;
        // Check if the selected edge is creating a cycle or not
        if(root(x) != root(y))
        {
            minimumCost += cost;
            union1(x, y);
        }    
    }
    return minimumCost;
}

int main()
{
    int x, y;
    long long weight, cost, minimumCost;
    initialize();
    cin >> nodes >> edges;
    for(int i = 0;i < edges;++i)
    {
        cin >> x >> y >> weight;
        p[i] = make_pair(weight, make_pair(x, y));
    }
    // Sort the edges in the ascending order
    sort(p, p + edges);
    minimumCost = kruskal(p);
    cout << minimumCost << endl;
    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: how to format big numbers with commas in c++ 
Cpp :: put function in cpp 
Cpp :: c++ set intersection 
Cpp :: even and odd in c++ 
Cpp :: potato 
Cpp :: c++ pass ofstream as argument 
Cpp :: minheap cpp stl 
Cpp :: arduino falling edge 
Cpp :: declare a tab c++ 
Cpp :: array 2d to 1d 
Cpp :: assignment operator with pointers c++ 
Cpp :: hide window c++ 
Cpp :: size of unordered_set 
Cpp :: erase range vector c++ 
Cpp :: C++ vector structure 
Cpp :: operator overloading in c++ 
Cpp :: minimum or maximum in array c++ 
Cpp :: split text c++ 
Cpp :: raspberry pi mount external hard drive 
Cpp :: error in c++ 
Cpp :: ue4 c++ switch enum 
Cpp :: online converter c++ to c 
Cpp :: function for reversing an array c++ stl 
Cpp :: creating large maps cpp 
Cpp :: time_t c++ stack overflow 
Cpp :: Mirror Inverse Program in c++ 
Cpp :: how to print double value up to 9 decimal places in c++ 
Cpp :: move semantics in c++ 
Cpp :: c++ over load oprator to print variable of clas 
Cpp :: sinh nhi phan c++ 
ADD CONTENT
Topic
Content
Source link
Name
9+1 =