Cod sursa(job #3357146)

Utilizator CosminDMRCosmin Damureanu CosminDMR Data 6 iunie 2026 17:24:28
Problema Sortare topologica Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<stdlib.h>

typedef struct listNode {
	int value;
	struct listNode* next;
} listNode;

typedef struct {
	int vertex_count;
	int edge_count;
	listNode** adjacency;
	int* in_degree;
} Graph;

listNode* create_node(int value) {
	listNode* newNode = (listNode*)malloc(sizeof(listNode));
	newNode->value = value;
	newNode->next = NULL;
	return newNode;
}

void add_to_list(listNode** list, int value) {
	listNode* newNode = create_node(value);

	if (*list == NULL) {
		*list = newNode;
		return;
	}

	newNode->next = *list;
	*list = newNode;
}

void read_graph(Graph* graph, const char* fileName) {
	FILE* input = fopen(fileName, "r");
	if (input == NULL) exit(1);

	fscanf(input, "%d %d", &graph->vertex_count, &graph->edge_count);
	graph->adjacency = (listNode**)malloc(graph->vertex_count * sizeof(listNode*));
	graph->in_degree = (int*)calloc(graph->vertex_count, sizeof(int));
	for (int i = 0; i < graph->vertex_count; i++)
		graph->adjacency[i] = NULL;
	for (int i = 0; i < graph->edge_count; i++) {
		int node1, node2;
		fscanf(input, "%d %d", &node1, &node2);
		add_to_list(&graph->adjacency[node1], node2);
	}

	fclose(input);
}

void calculate_in_degree(Graph* graph) {
	for (int i = 0; i < graph->vertex_count; i++)
		for (listNode* p = graph->adjacency[i]; p != NULL; p = p->next)
			graph->in_degree[p->value]++;
}

void topo_sort(Graph graph, const char* fileName) {
	FILE* output = fopen(fileName, "w");
	if (output == NULL) exit(2);

	for (int i = 0; i < graph.vertex_count; i++)
		if (graph.in_degree[i] == 0) {
			fprintf(output, "%d ", i + 1);
			graph.in_degree[i] = -1;
			for (listNode* p = graph.adjacency[i]; p != NULL; p = p->next)
				graph.in_degree[p->value]--;
		}
}

int main() {
	Graph graph;
	read_graph(&graph, "sortaret.in");
	calculate_in_degree(&graph);
	topo_sort(graph, "sortaret.out");

	return 0;
}