Advertisement
Guest User

Untitled

a guest
May 10th, 2014
431
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.48 KB | None | 0 0
  1. // C++ program for Prim's MST for adjacency list representation of graph that Michael Gates is failing at modifying
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <limits.h>
  6. #include <fstream>
  7. #include <iostream>
  8. using namespace std;
  9.  
  10. int weightTotal;
  11.  
  12. // A structure to represent a node in adjacency list
  13. struct AdjListNode
  14. {
  15. int dest;
  16. int weight;
  17. struct AdjListNode* next;
  18. };
  19.  
  20. // A structure to represent an adjacency liat
  21. struct AdjList
  22. {
  23. struct AdjListNode *head; // pointer to head node of list
  24. };
  25.  
  26. // A structure to represent a graph. A graph is an array of adjacency lists.
  27. // Size of array will be V (number of vertices in graph)
  28. struct Graph
  29. {
  30. int V;
  31. struct AdjList* array;
  32. };
  33.  
  34. // A utility function to create a new adjacency list node
  35. struct AdjListNode* newAdjListNode(int dest, int weight)
  36. {
  37. struct AdjListNode* newNode =
  38. (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
  39. newNode->dest = dest;
  40. newNode->weight = weight;
  41. newNode->next = NULL;
  42. return newNode;
  43. }
  44.  
  45. // A utility function that creates a graph of V vertices
  46. struct Graph* createGraph(int V)
  47. {
  48. struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
  49. graph->V = V;
  50.  
  51. // Create an array of adjacency lists. Size of array will be V
  52. graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
  53.  
  54. // Initialize each adjacency list as empty by making head as NULL
  55. for (int i = 0; i < V; ++i)
  56. graph->array[i].head = NULL;
  57.  
  58. return graph;
  59. }
  60.  
  61. // Adds an edge to an undirected graph
  62. void addEdge(struct Graph* graph, int src, int dest, int weight)
  63. {
  64. // Add an edge from src to dest. A new node is added to the adjacency
  65. // list of src. The node is added at the begining
  66. struct AdjListNode* newNode = newAdjListNode(dest, weight);
  67. newNode->next = graph->array[src].head;
  68. graph->array[src].head = newNode;
  69.  
  70. // Since graph is undirected, add an edge from dest to src also
  71. newNode = newAdjListNode(src, weight);
  72. newNode->next = graph->array[dest].head;
  73. graph->array[dest].head = newNode;
  74. }
  75.  
  76. // Structure to represent a min heap node
  77. struct MinHeapNode
  78. {
  79. int v;
  80. int key;
  81. };
  82.  
  83. // Structure to represent a min heap
  84. struct MinHeap
  85. {
  86. int size; // Number of heap nodes present currently
  87. int capacity; // Capacity of min heap
  88. int *pos; // This is needed for decreaseKey()
  89. struct MinHeapNode **array;
  90. };
  91.  
  92. // A utility function to create a new Min Heap Node
  93. struct MinHeapNode* newMinHeapNode(int v, int key)
  94. {
  95. struct MinHeapNode* minHeapNode =
  96. (struct MinHeapNode*) malloc(sizeof(struct MinHeapNode));
  97. minHeapNode->v = v;
  98. minHeapNode->key = key;
  99. return minHeapNode;
  100. }
  101.  
  102. // A utilit function to create a Min Heap
  103. struct MinHeap* createMinHeap(int capacity)
  104. {
  105. struct MinHeap* minHeap =
  106. (struct MinHeap*) malloc(sizeof(struct MinHeap));
  107. minHeap->pos = (int *)malloc(capacity * sizeof(int));
  108. minHeap->size = 0;
  109. minHeap->capacity = capacity;
  110. minHeap->array =
  111. (struct MinHeapNode**) malloc(capacity * sizeof(struct MinHeapNode*));
  112. return minHeap;
  113. }
  114.  
  115. // A utility function to swap two nodes of min heap. Needed for min heapify
  116. void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
  117. {
  118. struct MinHeapNode* t = *a;
  119. *a = *b;
  120. *b = t;
  121. }
  122.  
  123. // A standard function to heapify at given idx
  124. // This function also updates position of nodes when they are swapped.
  125. // Position is needed for decreaseKey()
  126. void minHeapify(struct MinHeap* minHeap, int idx)
  127. {
  128. int smallest, left, right;
  129. smallest = idx;
  130. left = 2 * idx + 1;
  131. right = 2 * idx + 2;
  132.  
  133. if (left < minHeap->size &&
  134. minHeap->array[left]->key < minHeap->array[smallest]->key )
  135. smallest = left;
  136.  
  137. if (right < minHeap->size &&
  138. minHeap->array[right]->key < minHeap->array[smallest]->key )
  139. smallest = right;
  140.  
  141. if (smallest != idx)
  142. {
  143. // The nodes to be swapped in min heap
  144. MinHeapNode *smallestNode = minHeap->array[smallest];
  145. MinHeapNode *idxNode = minHeap->array[idx];
  146.  
  147. // Swap positions
  148. minHeap->pos[smallestNode->v] = idx;
  149. minHeap->pos[idxNode->v] = smallest;
  150.  
  151. // Swap nodes
  152. swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
  153.  
  154. minHeapify(minHeap, smallest);
  155. }
  156. }
  157.  
  158. // A utility function to check if the given minHeap is ampty or not
  159. int isEmpty(struct MinHeap* minHeap)
  160. {
  161. return minHeap->size == 0;
  162. }
  163.  
  164. // Standard function to extract minimum node from heap
  165. struct MinHeapNode* extractMin(struct MinHeap* minHeap)
  166. {
  167. if (isEmpty(minHeap))
  168. return NULL;
  169.  
  170. // Store the root node
  171. struct MinHeapNode* root = minHeap->array[0];
  172.  
  173. // Replace root node with last node
  174. struct MinHeapNode* lastNode = minHeap->array[minHeap->size - 1];
  175. minHeap->array[0] = lastNode;
  176.  
  177. // Update position of last node
  178. minHeap->pos[root->v] = minHeap->size-1;
  179. minHeap->pos[lastNode->v] = 0;
  180.  
  181. // Reduce heap size and heapify root
  182. --minHeap->size;
  183. minHeapify(minHeap, 0);
  184.  
  185. return root;
  186. }
  187.  
  188. // Function to decreasy key value of a given vertex v. This function
  189. // uses pos[] of min heap to get the current index of node in min heap
  190. void decreaseKey(struct MinHeap* minHeap, int v, int key)
  191. {
  192. // Get the index of v in heap array
  193. int i = minHeap->pos[v];
  194.  
  195. // Get the node and update its key value
  196. minHeap->array[i]->key = key;
  197.  
  198. // Travel up while the complete tree is not hepified.
  199. // This is a O(Logn) loop
  200. while (i && minHeap->array[i]->key < minHeap->array[(i - 1) / 2]->key)
  201. {
  202. // Swap this node with its parent
  203. minHeap->pos[minHeap->array[i]->v] = (i-1)/2;
  204. minHeap->pos[minHeap->array[(i-1)/2]->v] = i;
  205. swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]);
  206.  
  207. // move to parent index
  208. i = (i - 1) / 2;
  209. }
  210. }
  211.  
  212. // A utility function to check if a given vertex
  213. // 'v' is in min heap or not
  214. bool isInMinHeap(struct MinHeap *minHeap, int v)
  215. {
  216. if (minHeap->pos[v] < minHeap->size)
  217. return true;
  218. return false;
  219. }
  220.  
  221. // A utility function used to print the constructed MST
  222. void printArr(int arr[], int n)
  223. {
  224. for (int i = 1; i < n; ++i)
  225. printf("%d - %d\n", arr[i], i);
  226. }
  227.  
  228. // The main function that constructs Minimum Spanning Tree (MST)
  229. // using Prim's algorithm
  230. void PrimMST(struct Graph* graph)
  231. {
  232. int V = graph->V;// Get the number of vertices in graph
  233. int parent[V]; // Array to store constructed MST
  234. int key[V]; // Key values used to pick minimum weight edge in cut
  235.  
  236. // minHeap represents set E
  237. struct MinHeap* minHeap = createMinHeap(V);
  238.  
  239. // Initialize min heap with all vertices. Key value of
  240. // all vertices (except 0th vertex) is initially infinite
  241. for (int v = 1; v < V; ++v)
  242. {
  243. parent[v] = -1;
  244. key[v] = INT_MAX;
  245. minHeap->array[v] = newMinHeapNode(v, key[v]);
  246. minHeap->pos[v] = v;
  247. }
  248.  
  249. // Make key value of 0th vertex as 0 so that it
  250. // is extracted first
  251. key[0] = 0;
  252. minHeap->array[0] = newMinHeapNode(0, key[0]);
  253. minHeap->pos[0] = 0;
  254.  
  255. // Initially size of min heap is equal to V
  256. minHeap->size = V;
  257.  
  258. // In the followin loop, min heap contains all nodes
  259. // not yet added to MST.
  260. while (!isEmpty(minHeap))
  261. {
  262. // Extract the vertex with minimum key value
  263. struct MinHeapNode* minHeapNode = extractMin(minHeap);
  264. int u = minHeapNode->v; // Store the extracted vertex number
  265.  
  266. // Traverse through all adjacent vertices of u (the extracted
  267. // vertex) and update their key values
  268. struct AdjListNode* pCrawl = graph->array[u].head;
  269. while (pCrawl != NULL)
  270. {
  271. int v = pCrawl->dest;
  272.  
  273. // If v is not yet included in MST and weight of u-v is
  274. // less than key value of v, then update key value and
  275. // parent of v
  276. if (isInMinHeap(minHeap, v) && pCrawl->weight < key[v])
  277. {
  278. key[v] = pCrawl->weight;
  279. parent[v] = u;
  280. decreaseKey(minHeap, v, key[v]);
  281. cout << "Weight = " << pCrawl->weight << endl;
  282. weightTotal += pCrawl->weight;
  283. }
  284. pCrawl = pCrawl->next;
  285. }
  286. }
  287.  
  288.  
  289. // print edges of MST
  290. printArr(parent, V);
  291.  
  292. }
  293.  
  294.  
  295. // Driver program to test above functions
  296. int main()
  297. {
  298.  
  299. const char* filename = "adjMatrix.txt";
  300. // declare a stream to read the file
  301. ifstream inFile(filename);
  302.  
  303. // Check if the file was opened or not
  304. if(!inFile)
  305. {
  306. cout << endl << "Failed to open file " << filename << endl;
  307. return 1;
  308. }
  309.  
  310. // read the number of nodes from the first line
  311. int numberOfNodes;
  312. inFile >> numberOfNodes;
  313.  
  314. struct Graph* graph = createGraph(numberOfNodes);
  315.  
  316. // read the numbers from the file one by one
  317. // and create the adjacency list out of it
  318. int n1,n2,n3;
  319. while(!inFile.eof())
  320. {
  321. inFile >> n1;
  322. inFile >> n2;
  323. inFile >> n3;
  324.  
  325. cout << "Adding: " << n1 << " " << n2 << " " << n3 << endl;
  326.  
  327. addEdge(graph, n1, n2, n3);
  328. }
  329.  
  330.  
  331. PrimMST(graph);
  332. cout << weightTotal;
  333.  
  334. return 0;
  335. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement