Cod sursa(job #2743021)

Utilizator andreea.dumitrascuAndreea Dumitrascu andreea.dumitrascu Data 22 aprilie 2021 14:43:17
Problema Algoritmul lui Dijkstra Scor 40
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define inf 99999999

int n, m;

typedef struct graphMatrix {
	int** costMatrix;
	int numNodes;
} graphMatrix;

typedef struct nodeDP {
	int node;
	int d;
	int parent;
	int visited;
} nodeDP;

int cmpNDP(const void* a, const void* b)
{
	nodeDP* A = (nodeDP*)a;
	nodeDP* B = (nodeDP*)b;
	return (A->d - B->d);
	/*if (A->d > B->d) return 1;
	if (A->d < B->d) return -1;*/
}
nodeDP* dijsktra(graphMatrix graph, int source)
{
	nodeDP* NDP = (nodeDP*)malloc(sizeof(nodeDP) * (graph.numNodes + 1));
	if (NDP == NULL)
		return NULL;
	for (int i = 1; i <= graph.numNodes; i++) {
		NDP[i].node = i;
		NDP[i].d = inf;
		NDP[i].parent = -1;
		NDP[i].visited = 0;
	}
	NDP[source].d = 0;
	int position = 1;
	while (position <= graph.numNodes) {
		for (int i = 1; i <= graph.numNodes; i++)
			if (i != source && graph.costMatrix[source][i] != inf) {
				int dist = NDP[source].d + graph.costMatrix[source][i];
				if (NDP[i].d > dist) {
					NDP[i].d = dist;
					NDP[i].parent = source;
				}
			}
		position++;
		int min = inf;
		NDP[source].visited = 1;
		for (int i = 1; i <= graph.numNodes; i++)
			if (NDP[i].d < min && !NDP[i].visited) {
				min = NDP[i].d;
				source = i;
			}
	}
	return NDP;
}
graphMatrix citire(char* filename)
{
	FILE* f = fopen(filename, "r");
	fscanf(f, "%d %d", &n, &m);
	graphMatrix graph;
	graph.numNodes = n;
	graph.costMatrix = (int**)malloc((n + 1) * sizeof(int*));
	for (int i = 1; i <= n; i++)
		graph.costMatrix[i] = (int*)malloc((n + 1) * sizeof(int));
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			graph.costMatrix[i][j] = inf;
	int a, b, c;
	for (int i = 0; i < m; i++) {
		fscanf(f, "%d %d %d", &a, &b, &c);
		graph.costMatrix[a][b] = c;
	}
	return graph;
}

int main()
{
	graphMatrix graph = citire("dijkstra.in");
	/*for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++)
			printf("%d ", graph.costMatrix[i][j]);
		printf("\n");
	}*/
	nodeDP* NDP = dijsktra(graph, 1);
	FILE* f = fopen("dijkstra.out", "w");
	for (int i = 2; i <= n; i++) {
		if (NDP[i].d == inf) {
			fprintf(f, "%d ", 0);
		} else {
			fprintf(f, "%d ", NDP[i].d);
		}
	}
	fclose(f);

	return 0;
}