|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +typedef struct { |
| 5 | + int* data; // Dynamic array to store elements |
| 6 | + int size; // Current size of the array |
| 7 | + int capacity; // Current allocated capacity |
| 8 | +} AdjList; |
| 9 | + |
| 10 | +typedef struct { |
| 11 | + AdjList* arr; // Array of AdjLists representing the graph |
| 12 | + int size; // Number of nodes in the graph |
| 13 | +} Graph; |
| 14 | + |
| 15 | +// Initialize an AdjList with a given capacity |
| 16 | +void initAdjList(AdjList* al, int initialCapacity) { |
| 17 | + al->data = (int*)malloc(initialCapacity * sizeof(int)); |
| 18 | + al->size = 0; |
| 19 | + al->capacity = initialCapacity; |
| 20 | +} |
| 21 | + |
| 22 | +// Adds a value to the AdjList, resizing only if necessary |
| 23 | +void pushBack(AdjList* al, int value) { |
| 24 | + if (al->size == al->capacity) { |
| 25 | + al->capacity = al->capacity == 0 ? 2 : al->capacity * 2; |
| 26 | + al->data = (int*)realloc(al->data, al->capacity * sizeof(int)); |
| 27 | + } |
| 28 | + al->data[al->size++] = value; |
| 29 | +} |
| 30 | + |
| 31 | +// Initialize a graph with a given size (number of nodes) |
| 32 | +void initGraph(Graph* g, int size) { |
| 33 | + g->arr = (AdjList*)malloc(size * sizeof(AdjList)); |
| 34 | + g->size = size; |
| 35 | + for (int i = 0; i < size; ++i) { |
| 36 | + initAdjList(&g->arr[i], 2); // Small initial capacity to reduce reallocations |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// Transpose the graph by reversing edges |
| 41 | +Graph solve(Graph* graph) { |
| 42 | + Graph ans; |
| 43 | + initGraph(&ans, graph->size); |
| 44 | + |
| 45 | + for (int i = 0; i < graph->size; ++i) { |
| 46 | + for (int j = 0; j < graph->arr[i].size; ++j) { |
| 47 | + int x = graph->arr[i].data[j]; |
| 48 | + pushBack(&ans.arr[x], i); // Add node 'i' to the list of node 'x' in the transposed graph |
| 49 | + } |
| 50 | + } |
| 51 | + return ans; |
| 52 | +} |
| 53 | + |
| 54 | +// Print the adjacency list of the graph |
| 55 | +void printGraph(Graph* g) { |
| 56 | + for (int i = 0; i < g->size; ++i) { |
| 57 | + printf("[ "); |
| 58 | + for (int j = 0; j < g->arr[i].size; ++j) { |
| 59 | + printf("%d ", g->arr[i].data[j]); |
| 60 | + } |
| 61 | + printf("]\n"); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +int main() { |
| 66 | + Graph graph; |
| 67 | + initGraph(&graph, 5); |
| 68 | + |
| 69 | + // Building the adjacency list for the input graph |
| 70 | + pushBack(&graph.arr[0], 1); |
| 71 | + pushBack(&graph.arr[0], 2); |
| 72 | + pushBack(&graph.arr[1], 4); |
| 73 | + pushBack(&graph.arr[2], 4); |
| 74 | + pushBack(&graph.arr[3], 1); |
| 75 | + pushBack(&graph.arr[3], 2); |
| 76 | + pushBack(&graph.arr[4], 3); |
| 77 | + |
| 78 | + Graph result = solve(&graph); |
| 79 | + printGraph(&result); |
| 80 | + return 0; |
| 81 | +} |
0 commit comments