Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct Edge {
- int src, dest, weight;
- };
- struct Graph {
- int V, E;
- struct Edge* edge;
- };
- struct Graph* createGraph(int V, int E) {
- struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
- graph->V = V;
- graph->E = E;
- graph->edge = (struct Edge*)malloc(E * sizeof(struct Edge));
- return graph;
- }
- struct subset {
- int parent;
- int rank;
- };
- int findParent(struct subset parent[], int i) {
- if (parent[i].parent != i)
- parent[i].parent = findParent(parent, parent[i].parent); // Path compression
- return parent[i].parent;
- }
- void unionSets(struct subset parent[], int x, int y) {
- int xroot = findParent(parent, x);
- int yroot = findParent(parent, y);
- if (parent[xroot].rank < parent[yroot].rank)
- parent[xroot].parent = yroot;
- else if (parent[xroot].rank > parent[yroot].rank)
- parent[yroot].parent = xroot;
- else {
- parent[yroot].parent = xroot;
- parent[xroot].rank++;
- }
- }
- int myComp(const void* a, const void* b) {
- struct Edge* a1 = (struct Edge*)a;
- struct Edge* b1 = (struct Edge*)b;
- return a1->weight - b1->weight;
- }
- void KruskalMST(struct Graph* graph) {
- int V = graph->V;
- struct Edge result[V - 1]; // MST will have V-1 edges
- int e = 0; // Index for result[]
- int i = 0; // Initial index for sorted edges
- qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
- struct subset* parent = (struct subset*)malloc(V * sizeof(struct subset));
- for (int v = 0; v < V; v++) {
- parent[v].parent = v;
- parent[v].rank = 0;
- }
- while (e < V - 1 && i < graph->E) {
- struct Edge next_edge = graph->edge[i++];
- int x = findParent(parent, next_edge.src);
- int y = findParent(parent, next_edge.dest);
- if (x != y) {
- result[e++] = next_edge;
- unionSets(parent, x, y);
- }
- }
- printf("Following are the edges in the constructed MST\n");
- for (i = 0; i < e; ++i)
- printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight);
- free(parent);
- }
- int main() {
- int V = 9, E = 14;
- struct Graph* graph = createGraph(V, E);
- graph->edge[0] = (struct Edge){0, 1, 4};
- graph->edge[1] = (struct Edge){0, 7, 8};
- graph->edge[2] = (struct Edge){1, 2, 8};
- graph->edge[3] = (struct Edge){1, 7, 11};
- graph->edge[4] = (struct Edge){2, 3, 7};
- graph->edge[5] = (struct Edge){2, 8, 2};
- graph->edge[6] = (struct Edge){2, 5, 4};
- graph->edge[7] = (struct Edge){3, 4, 9};
- graph->edge[8] = (struct Edge){3, 5, 14};
- graph->edge[9] = (struct Edge){4, 5, 10};
- graph->edge[10] = (struct Edge){5, 6, 2};
- graph->edge[11] = (struct Edge){6, 7, 1};
- graph->edge[12] = (struct Edge){6, 8, 6};
- graph->edge[13] = (struct Edge){7, 8, 7};
- KruskalMST(graph);
- free(graph->edge);
- free(graph);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement