Code is not working

I have tried to do the same code but it doesn’t seem to work. please tell me how to share here to understand what went wrong?

Please share your code

how to share here, tell me the process?

Copy your code here https://ide.codingblocks.com/, click on the File->Save. A new link will be generated at top, share that link here.

#include <bits/stdc++.h> using namespace std; class dsu{ int *parent; int *rank; public: dsu(int u){ parent = new int [u]; rank = new int[u]; for(int i = 0; i < u ; i++){ parent[i] = -1; rank[i] = 1; } } int find(int x){ if(parent[x]==-1){ return x; } return parent[x] = find(parent[x]); } void unite(int x, int y){ int s1 = find(x); int s2 = find(y); if(s1!=s2){ if(rank[s1]<rank[s2]){ parent[s1] = s2; rank[s2]+=rank[s1]; } else { parent[s2] = s1; rank[s1]+=rank[s2]; } } } }; class graph{ vector<vector> edgelist; int v; public: graph(int v){ this->v = v; } void addedge(int w, int x, int y){ edgelist.push_back({w,x,y}); } int krusksal() { sort(edgelist.begin(),edgelist.end()); int ans = 0; dsu s(v); for(auto x: edgelist) { int w = x[0]; int xc = x[1]; int yc = x[2]; if(s.find(xc)!=s.find(yc)) { s.unite(xc,yc); ans+=w; } } return ans; } }; int main() { graph g(4); g.addedge(0,1,1); g.addedge(1,3,3); g.addedge(3,2,4); g.addedge(2,0,2); g.addedge(0,3,2); g.addedge(1,2,2); cout<<g.krusksal()<<endl; }

Please do the above method, that way your code would be readable.

hello, i did it the way you mentioned, could you tell me why am i gettng segmentation fault

Yes I am checking, please give me some time.

Now it works https://ide.codingblocks.com/s/420791. Actually you are using a nodes from 0 to 4, but your graph has only 4 nodes, so that is causing segmentation fault.

Oh actually, weight column has to be 3rd. See how sir passes the values in addedge function. So make changes there.
You are doing

void addedge(int w, int x, int y){
    edgelist.push_back({w,x,y});
}

But you need to do

void addedge(int x, int y, int w){
    edgelist.push_back({w,x,y});
}

Like this https://ide.codingblocks.com/s/420798

but why does that give error i mean it only matters that we pass it correctly in the vector right? as in the order of parameters in function how does it matter’, i am quite unsure so i just wanted to clarify

sorry i understood, i was assuming that the input sir is taking in the video is weight first but it is x and y then w. Thanks alot!

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.