Cod sursa(job #1953052)

Utilizator SanteCiolosSante Ciolos SanteCiolos Data 4 aprilie 2017 16:51:33
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <list>
#include <queue>
#include <iostream>
#include <fstream>

#define Inf 0x3f3f3f3f

using namespace std;

class Graph
{
public:
    int V;
    list<pair<int, int>> *adj;

    Graph(int V);
    void addEdge(int u, int v, int w);
    void shortestPath(int s);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<pair<int, int>> [V];
}

void Graph::addEdge(int u, int v, int w)
{
    adj[u].push_back(make_pair(v, w));
    adj[v].push_back(make_pair(u, w));
}

void Graph::shortestPath(int src)
{
    ofstream out("dijkstra.out");
    priority_queue<pair<int, int>, vector<pair<int, int>> , greater<pair<int, int>>> pq;
    vector<int> dist(V, Inf);

    pq.push(make_pair(0, src));
    dist[src] = 0;

    while (!pq.empty())
    {
        int u = pq.top().second;
        pq.pop();

        list<pair<int, int>>::iterator i;
        for (i = adj[u].begin(); i != adj[u].end(); ++i)
        {
            int v = (*i).first;
            int weight = (*i).second;

            if(dist[v] > dist[u] + weight)
            {
                dist[v] = dist[u] + weight;
                pq.push(make_pair(dist[v], v));
            }
        }
    }

    for (int i = 2; i < V; ++i)
    {
        out << dist[i] << " ";
    }
}

int main()
{
    ifstream in("dijkstra.in");
    int n, m;
    int x, y, c;

    in >> n >> m;

    Graph g(n + 1);

    while(in >> x >> y >> c)
    {
        g.addEdge(x, y, c);
    }

    g.shortestPath(1);

    return 0;
}