Cod sursa(job #2528782)

Utilizator andreichitu7Andrei andreichitu7 Data 22 ianuarie 2020 16:16:19
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.73 kb
/// A C++ program for Dijkstra's single source shortest path algorithm.
// The program is for adjacency matrix representation of the graph
#include <iostream>
#include <limits.h>
#include <stdio.h>
#include <fstream>
using namespace std;
ifstream f ("dijkstra.in");
ofstream g ("dijkstra.out");

// Number of vertices in the graph
int  N,l,i,c,nm,graph[55][55]={{0},{0}},d;

// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool viz[])
{
    // Initialize min value
    int min = INT_MAX, min_index;

    for (int v = 1; v <= N; v++)
        if (viz[v] == false && dist[v] <= min)
            {min = dist[v]; min_index = v;}

    return min_index;
}

// A utility function to print the constructed distance array
int printSolution(int dist[])
{
    //printf("Vertex \t\t Distance from Source\n");
    for (int i = 2; i <= N; i++)
        g<<dist[i]<<" ";
}

// Function that implements Dijkstra's single source shortest path algorithm
// for a graph represented using adjacency matrix representation
void dijkstra(int graph[55][55], int src)
{
    int dist[N]; // The output array.  dist[i] will hold the shortest
    // distance from src to i

    bool viz[N]; // sptSet[i] will be true if vertex i is included in shortest
    // path tree or shortest distance from src to i is finalized

    // Initialize all distances as INFINITE and stpSet[] as false
    for (int i = 1; i <= N; i++)
        dist[i] = INT_MAX, viz[i] = false;

    // Distance of source vertex from itself is always 0
    dist[src] = 0;

    // Find shortest path for all vertices
    for (int count = 1; count <= N - 1; count++) {
        // Pick the minimum distance vertex from the set of vertices not
        // yet processed. u is always equal to src in the first iteration.
        int u = minDistance(dist, viz);

        // Mark the picked vertex as processed
        viz[u] = true;

        // Update dist value of the adjacent vertices of the picked vertex.
        for (int v = 1; v <= N; v++)

            // Update dist[v] only if is not in sptSet, there is an edge from
            // u to v, and total weight of path from src to  v through u is
            // smaller than current value of dist[v]
            if (!viz[v] && graph[u][v]>=1 && dist[u] != INT_MAX
                && dist[u] + graph[u][v] < dist[v])
                dist[v] = dist[u] + graph[u][v];
    }

    // print the constructed distance array
    printSolution(dist);


}


// driver program to test above function
int main()
{f>>N>>nm;
for(i=1;i<=nm;i++)
{f>>l>>c>>d;
 graph[l][c]=d;
}
    dijkstra(graph, 1);

    return 0;
}