Pagini recente » Cod sursa (job #2740438) | Istoria paginii utilizator/banescueduard | Cod sursa (job #3207974) | Cod sursa (job #2425542) | Cod sursa (job #2741479)
#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( graphMatrix graph, int source )
{
nodeNDP* NDP = (nodeNDP*)malloc( sizeof( nodeNDP ) * ( N + 1 ) );
bool visited[5000] = { 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 );
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 );
return 0;
}