Cod sursa(job #3274644)

Utilizator denisdalanDenis Dalan denisdalan Data 7 februarie 2025 22:49:28
Problema Sortare topologica Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <stdio.h>
#include <stdlib.h>

struct AdjListNode {
	int dest;
	struct AdjListNode* next;
};

struct Graph {
	int numVertices;
	struct AdjListNode** array;
	int *inDegree;
};

struct AdjListNode* newAdjListNode(int dest) {
	struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
	newNode->dest = dest;
	newNode->next = NULL;
	return newNode;
}

struct Graph* createGraph(int numVertices) {
	struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
	graph->numVertices = numVertices;
	graph->array = (struct AdjListNode**)malloc(numVertices * sizeof(struct AdjListNode*));
	graph->inDegree = (int*)calloc(numVertices, sizeof(int)); // Initialize to 0

	for (int i = 0; i < numVertices; ++i)
		graph->array[i] = NULL;

	return graph;
}

void addEdge(struct Graph* graph, int src, int dest) {
	struct AdjListNode* newNode = newAdjListNode(dest);
	newNode->next = graph->array[src];
	graph->array[src] = newNode;

	graph->inDegree[dest]++;
}

void printGraph (struct Graph* graph)
{
	for (int v = 0; v < graph->numVertices; ++v) {
		struct AdjListNode* current = graph->array[v];
		printf("Adjacency list of vertex %d\nhead ", v);
		while (current) {
			printf("-> %d ", current->dest);
			current = current->next;
		}
		printf("\n");
	}
}

int l[50000];
int s[50000];

int main() {
	FILE *ifptr;
	FILE *ofptr;

	ifptr = fopen("sortaret.in", "r");
	ofptr = fopen("sortaret.out", "w");

	int n, m, i, j, u, v, k;	

	fscanf(ifptr, "%d %d", &n, &m);	

	struct Graph* graph = createGraph(n+1);

	for (i = 0; i < m; ++i) {
		fscanf(ifptr, "%d %d", &u, &v);
		addEdge(graph, u, v);
	}

	k = 0; //length of s
	for (i = 1; i <= n; ++i) {
		if (graph->inDegree[i] == 0) {
			s[k] = i;
			//printf("%d", s[k]);
			++k;
		}
	}

	for (int i = 0; i < k; ++i)
		//printf("%d ", s[i]);

	//printf("\n");

	j = 0; //length of l
	while (k != 0)
	{
		int node = s[k-1];
		l[j] = node;
		++j;
		--k;
		struct AdjListNode* current = graph->array[node];
		//printf("node %d\n", node);
		while (current)
		{
			int mnode = current->dest;
			//printf("%d", current->dest);
			graph->inDegree[mnode]--;

			if (graph->inDegree[mnode] == 0)
			{
				s[k] = mnode;
				++k;
				//printf("%d", mnode);
			}

			current = current->next;
		}
	}
	
	for (int i = 0; i < j; ++i)
		fprintf(ofptr, "%d ", l[i]);

	//printGraph(graph);

	fclose(ifptr);
	fclose(ofptr);
	return 0;
}