0
vector<int> pr;
vector<int> sz;
vector<vector<int>> ans;
    
void mset(int u)
{
    pr[u] = u ;
    sz[u] = 1;
}

int fset(int u)
{
    if(pr[u] == u)
    return u;
    
    return pr[u] = fset(pr[u]);
}

void uset(int u , int v)
{
    u = fset(u);
    v = fset(v);
    if(u != v)
    {
        if(sz[u] < sz[v])
        swap(u , v);
        
        sz[u] += sz[v];
        pr[v] = pr[u];
    }
}

int com(vector<int> a , vector<int> b)
{
    return a[0] > b[0];
}

int spanningTree(int V, vector<vector<int>> adj[])
{
    // code here
    for(int i = 0 ; i < V ; i++)
    {
        mset(i);
    }
    int cost = 0;
    for(int i = 0 ; i < V ;i++)
    {
        for(auto j : adj[i] )
        {
            ans.push_back( {j[1],j[0],i} );
        }
    }
    
    sort(ans.begin() , ans.end());
    for(auto i : ans )
    {
        int w = i[0];
        int u = i[1];
        int v = i[2];
        u = fset(u);
        v = fset(v);
        if(v == u)
        {
            continue ;
        }
        else
        {
            cost += w;
            uset(u , v);
        }
        
        
        
    }
    return cost ;
}

// i was trying to do mst using Kruskal algo on gfg practice , there the graph (weighted) was implemented using array of 2d vector , so i tried to convert it into a 2d vector having first element as weight so that it can easily get sorted when using sort() function but i am getting segmentation fault , i dont know what is the bug .... plz help find the problem in code .

B G
  • 1
  • You never seem to initialize the `pr` or `sz` vectors. Which means they will be empty, and all indexing into them will be out of bounds and lead to *undefined behavior*. – Some programmer dude Nov 20 '21 at 11:36
  • To be honest, the code you show smells (in a bad way) of so-called "competition" or "online judge" site exercise. And if you're new to C++ (or programming in general) you should not use such sites as a way to learn, they are not any kind of learning or teaching resource. Using them as such can be more harmfull to your learning than useful. Read [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) and take classes, and don't look at such sites in a couple of years. – Some programmer dude Nov 20 '21 at 11:39

0 Answers0