|
| 1 | +#include <iostream> |
| 2 | +#include<bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | +class edge{ |
| 5 | + public : |
| 6 | + int source; |
| 7 | + int destination; |
| 8 | + int weight; |
| 9 | +}; |
| 10 | + |
| 11 | +bool compare(edge e1, edge e2) |
| 12 | +{ |
| 13 | + return e1.weight < e2.weight; |
| 14 | +} |
| 15 | + |
| 16 | +int findParent(int v, int* parent) |
| 17 | +{ |
| 18 | + if(parent[v] == v) |
| 19 | + return v; |
| 20 | + |
| 21 | + return findParent(parent[v],parent); |
| 22 | +} |
| 23 | + |
| 24 | +void kruskals(edge* input, int V, int E) |
| 25 | +{ |
| 26 | + sort(input,input+E,compare); |
| 27 | + |
| 28 | + edge* output = new edge[V-1]; |
| 29 | + int *parent = new int[V]; |
| 30 | + |
| 31 | + for(int i = 0; i < V; i++) |
| 32 | + parent[i] = i; |
| 33 | + |
| 34 | + int count = 0; |
| 35 | + int i = 0; |
| 36 | + |
| 37 | + while(count < V-1) |
| 38 | + { |
| 39 | + int srcParent = findParent(input[i].source,parent); |
| 40 | + int destParent = findParent(input[i].destination,parent); |
| 41 | + if(srcParent != destParent) |
| 42 | + { |
| 43 | + output[count++] = input[i]; |
| 44 | + parent[srcParent] = destParent; |
| 45 | + } |
| 46 | + i++; |
| 47 | + } |
| 48 | + |
| 49 | + for(int i = 0; i < V-1; i++) |
| 50 | + { |
| 51 | + if(output[i].source < output[i].destination) |
| 52 | + cout<<output[i].source<<" "<<output[i].destination<<" "<<output[i].weight<<endl; |
| 53 | + else |
| 54 | + cout<<output[i].destination<<" "<<output[i].source<<" "<<output[i].weight<<endl; |
| 55 | + |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | + |
| 60 | +int main() |
| 61 | +{ |
| 62 | + int V, E,s,d,w; |
| 63 | + cin >> V >> E; |
| 64 | + /* Write Your Code Here |
| 65 | + Complete the Rest of the Program |
| 66 | + You have to Print the output yourself |
| 67 | + */ |
| 68 | + edge* input = new edge[E]; |
| 69 | + for(int i = 0; i<E; i++) |
| 70 | + { |
| 71 | + cin>>s>>d>>w; |
| 72 | + input[i].source = s; |
| 73 | + input[i].destination = d; |
| 74 | + input[i].weight = w; |
| 75 | + } |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + kruskals(input,V,E); |
| 80 | + |
| 81 | + return 0; |
| 82 | +} |
0 commit comments