Cod sursa(job #2634988)

Utilizator zerolightningIon Bobescu zerolightning Data 12 iulie 2020 20:29:15
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <list>
#include <vector>

using namespace std;

#define INFINITY INT_MAX
#define MAX_N 50001

int n,m;
list<pair<int,int>> *links;

void addLink(int origin,int destination, int weight)
{
    links[origin].push_back(make_pair(weight,destination));
    links[destination].push_back(make_pair(weight,origin));
}

int Dijkstra(int source, int destination)
{
    priority_queue< pair<int,int>,
                    vector< pair<int,int> >,
                    greater< pair<int,int> >
                    > pq;
    pq.push(make_pair(0, source));

    vector<int> dist(n,INFINITY);
    dist[source] = 0;
    while(!pq.empty())
    {
        int u = pq.top().second;
        pq.pop();
        for(auto it = links[u].begin(); it != links[u].end(); it++)
        {
            int v = (*it).second;
            int weight = (*it).first;
            if( dist[v] > dist[u] + weight )
            {
                if( v == destination)
                {
                    return dist[u] + weight;
                }
                else
                {
                    dist[v] = dist[u] + weight;
                    pq.push(make_pair(dist[v],v));
                }
            }
        }
    }
    return 0;
}

int main()
{
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");
    // read
    f>>n;
    links = new list< pair<int,int> >[n];
    f>>m;

    for(int i = 0; i < m; i++)
    {
        int o,d,w;
        f>>o;
        f>>d;
        f>>w;
        addLink(o-1,d-1,w);
    }

    for(int i = 1; i <= n; i++)
    {
        cout<<"[0 -> "<<i<<"] = "<<Dijkstra(0,i)<<endl;
    }
}