Cod sursa(job #2741463)

Utilizator radu01Toader Radu Marian radu01 Data 15 aprilie 2021 23:53:04
Problema Algoritmul lui Dijkstra Scor 40
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.25 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 );
	int i, j;
	for ( i = 0; i < N; i++ ) {
		graph.costMatrix[i] = (int*)malloc( sizeof( int ) * N );
		for ( j = 0; j < N; j++ ) {
			if ( i == j ) {
				graph.costMatrix[i][j] = 0;
				continue;
			}
			graph.costMatrix[i][j] = inf;
		}
	}
	short A, B, C;
	for ( 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( int source )
{
	graphMatrix graph = readFile( "dijkstra.in" );
	nodeNDP* NDP = (nodeNDP*)malloc( sizeof( nodeNDP ) * ( N + 1 ) );

	bool visited[50000] = { 0 };
	for ( int i = 1; i <= N; i++ ) {
		NDP[i].node = i;
		NDP[i].d = inf;
		NDP[i].parent = -1;
	}
	source--;
	NDP[source].d = 0;
	int count = 1;
	int min;
	int i;
	while ( count <= N - 1 ) {
		for ( 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++;
		min = inf;
		for ( 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 );
	nodeNDP* NDP = dijkstra( 1 );
	FILE* g = fopen( "dijkstra.out", "w" );
	if ( g == NULL ) {
		printf( "ERROR AT OPENING OUT FILE" );
		return 0;
	}
	for ( int i = 1; i < N; i++ ) {
		if ( NDP[i].d == inf ) {
			fprintf( g, "%d ", 0 );
		} else {
			fprintf( g, "%d ", NDP[i].d );
		}
	}

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

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

	return 0;
}