|
| 1 | +#include <iostream> |
| 2 | +#include<bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | +int findMinVertex(int* weights, bool* visited, int V) |
| 5 | +{ |
| 6 | + int minVertex = -1; |
| 7 | + for(int i = 0; i < V; i++) |
| 8 | + { |
| 9 | + if(visited[i] == false) |
| 10 | + { |
| 11 | + if(minVertex == -1 || weights[i] < weights[minVertex]) |
| 12 | + minVertex = i; |
| 13 | + } |
| 14 | + } |
| 15 | + return minVertex; |
| 16 | + |
| 17 | +} |
| 18 | +void prim(int** adjMatrix, int V) |
| 19 | +{ |
| 20 | + bool* visited = new bool[V]; |
| 21 | + int* parents = new int[V]; |
| 22 | + int* weights = new int[V]; |
| 23 | + |
| 24 | + for(int i = 0; i < V; i++){ |
| 25 | + weights[i] = INT_MAX; |
| 26 | + visited[i] = false; |
| 27 | + } |
| 28 | + |
| 29 | + parents[0] = -1; |
| 30 | + weights[0] = 0; |
| 31 | + |
| 32 | + for(int i = 0; i < V - 1; i++) |
| 33 | + { //find minVertex |
| 34 | + int minVertex = findMinVertex(weights,visited,V); |
| 35 | + visited[minVertex] = true; |
| 36 | + //explore unvisited neighbours |
| 37 | + for(int j = 0; j < V; j++) |
| 38 | + { |
| 39 | + if(adjMatrix[minVertex][j] != 0 && !visited[j]) |
| 40 | + { |
| 41 | + if(adjMatrix[minVertex][j] < weights[j]) |
| 42 | + { |
| 43 | + weights[j] = adjMatrix[minVertex][j]; |
| 44 | + parents[j] = minVertex; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + //printing |
| 52 | + for(int i = 1; i < V; i++) |
| 53 | + { |
| 54 | + if(parents[i] < i) |
| 55 | + cout << parents[i] << " " << i << " " << weights[i] << endl; |
| 56 | + else |
| 57 | + cout << i << " " << parents[i] << " " << weights[i] << endl; |
| 58 | + |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + } |
| 65 | +int main() |
| 66 | +{ |
| 67 | + int V, E, tempX, tempY; |
| 68 | + cin >> V >> E; |
| 69 | + |
| 70 | + /* |
| 71 | + |
| 72 | + Write Your Code Here |
| 73 | + Complete the Rest of the Program |
| 74 | + You have to Print the output yourself |
| 75 | + |
| 76 | + */ |
| 77 | + int ** adjMatrix = new int*[V]; |
| 78 | + for(int i = 0; i < V; i++) |
| 79 | + { |
| 80 | + adjMatrix[i] = new int[V]; |
| 81 | + for(int j = 0; j < V; j++) |
| 82 | + adjMatrix[i][j] = 0; |
| 83 | + } |
| 84 | + |
| 85 | + |
| 86 | + for(int i = 0; i<E; i++) |
| 87 | + {int s,d,w; |
| 88 | + cin>>s>>d>>w; |
| 89 | + adjMatrix[s][d] = w; |
| 90 | + adjMatrix[d][s] = w; |
| 91 | + } |
| 92 | + |
| 93 | + prim(adjMatrix,V); |
| 94 | + |
| 95 | + for(int i = 0; i < V; i++) |
| 96 | + delete [] adjMatrix[i]; |
| 97 | + |
| 98 | + delete [] adjMatrix; |
| 99 | + |
| 100 | + return 0; |
| 101 | +} |
0 commit comments