Facebook
From chenqin, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 100
  1. Minimum Spanning Tree using Prim's Algorithm :-
  2.  
  3. // A C / C++ program for Prim's Minimum
  4. // Spanning Tree (MST) algorithm. The program is
  5. // for adjacency matrix representation of the graph
  6. #include <stdio.h>
  7. #include <limits.h>
  8. #include<stdbool.h>
  9. // Number of vertices in the graph
  10. #define V 5
  11.  
  12. // A utility function to find the vertex with
  13. // minimum key value, from the set of vertices
  14. // not yet included in MST
  15. int minKey(int key[], bool mstSet[])
  16. {
  17. // Initialize min value
  18. int min = INT_MAX, min_index;
  19.  
  20. for (int v = 0; v < V; v++)
  21.    if (mstSet[v] == false && key[v] < min)
  22.        min = key[v], min_index = v;
  23.  
  24. return min_index;
  25. }
  26.  
  27. // A utility function to print the
  28. // constructed MST stored in parent[]
  29. int printMST(int parent[], int n, int graph[V][V])
  30. {
  31. printf("Edge \tWeight\n");
  32. for (int i = 1; i < V; i++)
  33.    printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
  34. }
  35.  
  36. // Function to construct and print MST for
  37. // a graph represented using adjacency
  38. // matrix representation
  39. void primMST(int graph[V][V])
  40. {
  41.    // Array to store constructed MST
  42.    int parent[V];
  43.    // Key values used to pick minimum weight edge in cut
  44.    int key[V];
  45.    // To represent set of vertices not yet included in MST
  46.    bool mstSet[V];
  47.  
  48.    // Initialize all keys as INFINITE
  49.    for (int i = 0; i < V; i++)
  50.        key[i] = INT_MAX, mstSet[i] = false;
  51.  
  52.    // Always include first 1st vertex in MST.
  53.    // Make key 0 so that this vertex is picked as first vertex.
  54.    key[0] = 0;  
  55.    parent[0] = -1; // First node is always root of MST
  56.  
  57.    // The MST will have V vertices
  58.    for (int count = 0; count < V-1; count++)
  59.    {
  60.        // Pick the minimum key vertex from the
  61.        // set of vertices not yet included in MST
  62.        int u = minKey(key, mstSet);
  63.  
  64.        // Add the picked vertex to the MST Set
  65.        mstSet[u] = true;
  66.  
  67.        // Update key value and parent index of
  68.        // the adjacent vertices of the picked vertex.
  69.        // Consider only those vertices which are not
  70.        // yet included in MST
  71.        for (int v = 0; v < V; v++)
  72.  
  73.        // graph[u][v] is non zero only for adjacent vertices of m
  74.        // mstSet[v] is false for vertices not yet included in MST
  75.        // Update the key only if graph[u][v] is smaller than key[v]
  76.        if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
  77.            parent[v] = u, key[v] = graph[u][v];
  78.    }
  79.  
  80.    // print the constructed MST
  81.    printMST(parent, V, graph);
  82. }
  83.  
  84.  
  85. // driver program to test above function
  86. int main()
  87. {
  88. /* Let us create the following graph
  89.        2 3
  90.    (0)--(1)--(2)
  91.    | / \ |
  92.    6| 8/ \5 |7
  93.    | /   \ |
  94.    (3)-------(4)
  95.            9       */
  96. int graph[V][V] = {{0, 2, 0, 6, 0},
  97.                    {2, 0, 3, 8, 5},
  98.                    {0, 3, 0, 0, 7},
  99.                    {6, 8, 0, 0, 9},
  100.                    {0, 5, 7, 9, 0}};
  101.  
  102.    // Print the solution
  103.    primMST(graph);
  104.  
  105.    return 0;
  106. }
  107.  
  108.  
  109. OutPut:-
  110.  
  111. Edge   Weight
  112. 0 - 1    2
  113. 1 - 2    3
  114. 0 - 3    6
  115. 1 - 4    5
  116. Minimum Spanning tree using Kruskal's Algorithm :-
  117.  
  118. // C++ program for Kruskal's algorithm to find Minimum Spanning Tree
  119. // of a given connected, undirected and weighted graph
  120. #include <stdio.h>
  121. #include <stdlib.h>
  122. #include <string.h>
  123.  
  124. // a structure to represent a weighted edge in graph
  125. struct Edge
  126. {
  127.    int src, dest, weight;
  128. };
  129.  
  130. // a structure to represent a connected, undirected
  131. // and weighted graph
  132. struct Graph
  133. {
  134.    // V-> Number of vertices, E-> Number of edges
  135.    int V, E;
  136.  
  137.    // graph is represented as an array of edges.
  138.    // Since the graph is undirected, the edge
  139.    // from src to dest is also edge from dest
  140.    // to src. Both are counted as 1 edge here.
  141.    struct Edge* edge;
  142. };
  143.  
  144. // Creates a graph with V vertices and E edges
  145. struct Graph* createGraph(int V, int E)
  146. {
  147.    struct Graph* graph = new Graph;
  148.    graph->V = V;
  149.    graph->E = E;
  150.  
  151.    graph->edge = new Edge[E];
  152.  
  153.    return graph;
  154. }
  155.  
  156. // A structure to represent a subset for union-find
  157. struct subset
  158. {
  159.    int parent;
  160.    int rank;
  161. };
  162.  
  163. // A utility function to find set of an element i
  164. // (uses path compression technique)
  165. int find(struct subset subsets[], int i)
  166. {
  167.    // find root and make root as parent of i
  168.    // (path compression)
  169.    if (subsets[i].parent != i)
  170.        subsets[i].parent = find(subsets, subsets[i].parent);
  171.  
  172.    return subsets[i].parent;
  173. }
  174.  
  175. // A function that does union of two sets of x and y
  176. // (uses union by rank)
  177. void Union(struct subset subsets[], int x, int y)
  178. {
  179.    int xroot = find(subsets, x);
  180.    int yroot = find(subsets, y);
  181.  
  182.    // Attach smaller rank tree under root of high
  183.    // rank tree (Union by Rank)
  184.    if (subsets[xroot].rank < subsets[yroot].rank)
  185.        subsets[xroot].parent = yroot;
  186.    else if (subsets[xroot].rank > subsets[yroot].rank)
  187.        subsets[yroot].parent = xroot;
  188.  
  189.    // If ranks are same, then make one as root and
  190.    // increment its rank by one
  191.    else
  192.    {
  193.        subsets[yroot].parent = xroot;
  194.        subsets[xroot].rank++;
  195.    }
  196. }
  197.  
  198. // Compare two edges according to their weights.
  199. // Used in qsort() for sorting an array of edges
  200. int myComp(const void* a, const void* b)
  201. {
  202.    struct Edge* a1 = (struct Edge*)a;
  203.    struct Edge* b1 = (struct Edge*)b;
  204.    return a1->weight > b1->weight;
  205. }
  206.  
  207. // The main function to construct MST using Kruskal's algorithm
  208. void KruskalMST(struct Graph* graph)
  209. {
  210.    int V = graph->V;
  211.    struct Edge result[V]; // Tnis will store the resultant MST
  212.    int e = 0; // An index variable, used for result[]
  213.    int i = 0; // An index variable, used for sorted edges
  214.  
  215.    // Step 1: Sort all the edges in non-decreasing
  216.    // order of their weight. If we are not allowed to
  217.    // change the given graph, we can create a copy of
  218.    // array of edges
  219.    qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
  220.  
  221.    // Allocate memory for creating V ssubsets
  222.    struct subset *subsets =
  223.        (struct subset*) malloc( V * sizeof(struct subset) );
  224.  
  225.    // Create V subsets with single elements
  226.    for (int v = 0; v < V; ++v)
  227.    {
  228.        subsets[v].parent = v;
  229.        subsets[v].rank = 0;
  230.    }
  231.  
  232.    // Number of edges to be taken is equal to V-1
  233.    while (e < V - 1)
  234.    {
  235.        // Step 2: Pick the smallest edge. And increment
  236.        // the index for next iteration
  237.        struct Edge next_edge = graph->edge[i++];
  238.  
  239.        int x = find(subsets, next_edge.src);
  240.        int y = find(subsets, next_edge.dest);
  241.  
  242.        // If including this edge does't cause cycle,
  243.        // include it in result and increment the index
  244.        // of result for next edge
  245.        if (x != y)
  246.        {
  247.            result[e++] = next_edge;
  248.            Union(subsets, x, y);
  249.        }
  250.        // Else discard the next_edge
  251.    }
  252.  
  253.    // print the contents of result[] to display the
  254.    // built MST
  255.    printf("Following are the edges in the constructed MST\n");
  256.    for (i = 0; i < e; ++i)
  257.        printf("%d -- %d == %d\n", result[i].src, result[i].dest,
  258.                                                result[i].weight);
  259.    return;
  260. }
  261.  
  262. // Driver program to test above functions
  263. int main()
  264. {
  265.    /* Let us create following weighted graph
  266.            10
  267.        0--------1
  268.        | \   |
  269.    6| 5\ |15
  270.        |   \ |
  271.        2--------3
  272.            4   */
  273.    int V = 4; // Number of vertices in graph
  274.    int E = 5; // Number of edges in graph
  275.    struct Graph* graph = createGraph(V, E);
  276.  
  277.  
  278.    // add edge 0-1
  279.    graph->edge[0].src = 0;
  280.    graph->edge[0].dest = 1;
  281.    graph->edge[0].weight = 10;
  282.  
  283.    // add edge 0-2
  284.    graph->edge[1].src = 0;
  285.    graph->edge[1].dest = 2;
  286.    graph->edge[1].weight = 6;
  287.  
  288.    // add edge 0-3
  289.    graph->edge[2].src = 0;
  290.    graph->edge[2].dest = 3;
  291.    graph->edge[2].weight = 5;
  292.  
  293.    // add edge 1-3
  294.    graph->edge[3].src = 1;
  295.    graph->edge[3].dest = 3;
  296.    graph->edge[3].weight = 15;
  297.  
  298.    // add edge 2-3
  299.    graph->edge[4].src = 2;
  300.    graph->edge[4].dest = 3;
  301.    graph->edge[4].weight = 4;
  302.  
  303.    KruskalMST(graph);
  304.  
  305.    return 0;
  306. }
  307.  
  308.