Cod sursa(job #1179857)

Utilizator SCBbestofSocaciu-Cumpanasu Bogdan SCBbestof Data 29 aprilie 2014 14:15:19
Problema Algoritmul lui Dijkstra Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.92 kb
 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

struct Edge
{
    int src, dest, weight;
};


struct Graph
{

    int V, E;


    struct Edge* edge;
};


struct Graph* createGraph(int V, int E)
{
    struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );
    graph->V = V;
    graph->E = E;

    graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );

    return graph;
}

void printArr(int dist[], int n)
{
    FILE *g = fopen("dijkstra.out","w");
    int i;
    printf("Vertex   Distance from Source\n");
    for (i = 0; i < n; ++i)
        fprintf(g,"%d \t\t %d\n", i, dist[i]);

    fclose(g);
}

void BellmanFord(struct Graph* graph, int src)
{
    int V = graph->V;
    int E = graph->E;
    int dist[V];
    int i,j;

    for (i = 0; i < V; i++)
        dist[i]   = INT_MAX;
    dist[src] = 0;

    for (i = 1; i <= V-1; i++)
    {
        for (j = 0; j < E; j++)
        {
            int u = graph->edge[j].src;
            int v = graph->edge[j].dest;
            int weight = graph->edge[j].weight;
            if (dist[u] + weight < dist[v])
                dist[v] = dist[u] + weight;
        }
    }


    for (i = 0; i < E; i++)
    {
        int u = graph->edge[i].src;
        int v = graph->edge[i].dest;
        int weight = graph->edge[i].weight;
        if (dist[u] + weight < dist[v])
            printf("Graph contains negative weight cycle");
    }

    printArr(dist, V);
}


int main()
{
    int i,V,E,a,b,cst;
    FILE *f = fopen("dijkstra.in","r");

    fscanf(f,"%d%d",&V,&E);
    struct Graph* graph = createGraph(V, E);

    for(i = 0 ; i < E ; ++i)
    {
        fscanf(f,"%d%d%d",&a,&b,&cst);
        graph->edge[i].src = a-1;
        graph->edge[i].dest = b-1;
        graph->edge[i].weight = cst;
    }

    BellmanFord(graph,0);

    fclose(f);

    return 0;
}