Cod sursa(job #2741453)

Utilizator radu01Toader Radu Marian radu01 Data 15 aprilie 2021 23:32:45
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int N, M;

#define inf 1000000001

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

typedef struct nodeNDP {
	int node;
	int d;
	int parent;
} nodeNDP;

graphMatrix readFile( const char* filename )
{
	graphMatrix graph;
	FILE* f = fopen( filename, "r" );

	fscanf( f, "%d %d", &N, &M );
	graph.costMatrix = (int**)malloc( sizeof( int* ) * N );
	for ( int i = 0; i < N; i++ ) {
		graph.costMatrix[i] = (int*)malloc( sizeof( int ) * N );
		for ( int j = 0; j < N; j++ ) {
			if ( i == j ) {
				graph.costMatrix[i][j] = 0;
				continue;
			}
			graph.costMatrix[i][j] = inf;
		}
	}
	short A, B, C;
	for ( int i = 0; i < M; i++ ) {
		fscanf( f, "%hd %hd %hd", &A, &B, &C );
		graph.costMatrix[A - 1][B - 1] = C;
	}

	fclose( f );
	return graph;
}

nodeNDP* dijkstra( graphMatrix graph, int source )
{
	nodeNDP* NDP = (nodeNDP*)malloc( sizeof( nodeNDP ) * ( N + 1 ) );
	bool visited[50000];
	for ( int i = 1; i <= N; i++ ) {
		NDP[i].node = i;
		NDP[i].d = inf;
		NDP[i].parent = -1;
		visited[i] = 0;
	}
	source--;
	NDP[source].d = 0;
	int count = 1;
	while ( count <= N - 1 ) {
		for ( int i = 0; i < N; i++ ) {
			if ( source != i && graph.costMatrix[source][i] != inf && visited[i] == 0 ) {
				int distance = NDP[source].d + graph.costMatrix[source][i];
				if ( distance < NDP[i].d ) {
					NDP[i].d = distance;
					NDP[i].parent = source;
				}
			}
		}
		visited[source] = 1;
		count++;
		int min = inf;
		for ( int i = 1; i <= N; i++ ) {
			if ( min > NDP[i].d && visited[i] == 0 ) {
				min = NDP[i].d;
				source = i;
			}
		}
	}
	return NDP;
}

int main()
{
	graphMatrix graph = readFile( "dijkstra.in" );
	nodeNDP* NDP = dijkstra( graph, 1 );
	FILE* f = fopen( "dijkstra.out", "w" );
	for ( int i = 1; i < N; i++ ) {
		if ( NDP[i].d == inf ) {
			fprintf( f, "%d ", 0 );
		} else {
			fprintf( f, "%d ", NDP[i].d );
		}
	}

	for ( int i = 0; i < N; i++ ) {
		free( graph.costMatrix[i] );
	}
	free( graph.costMatrix );
	free( NDP );
	fclose( f );

	//printf( "size of bool %d\n", sizeof( bool ) );
	//printf( "size of int %d\n", sizeof( int ) );

	return 0;
}