Cod sursa(job #1981995)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 17 mai 2017 15:22:48
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <set>

using namespace std;

const int nMax = 50005;
const int mMax = 250005;
const int INF = (1 << 30);

struct arc
{
    arc(int tind = 0, int tcost = 0)
    {
        ind = tind;
        cost = tcost;
    }
    int ind, cost;
};

int n, m;
vector<arc> vecini[nMax];
int dp[nMax];
bool viz[nMax];

void citire()
{
    ifstream in("dijkstra.in");
    in >> n >> m;
    int a, b, c;
    for(int i = 1; i <= m; ++i)
    {
        in >> a >> b >> c;
        vecini[a].push_back(arc(b, c));

    }
    in.close();
}

void rezolvare()
{
    const int start = 1; //nodul de la care plecam
    for(int i = 1; i <= n; ++i)
        dp[i] = INF;

    set<pair<int, int> > q;
    dp[start] = 0;
    q.insert(make_pair(0, start));

    pair<int, int> p;
    int current, cost;
    while(q.empty() == false)
    {
        p = *q.begin();
        q.erase(p);

        current = p.second;
        cost = p.first;
        viz[current] = true;

        for(auto &v:vecini[current])
        {
            if(viz[v.ind])
                continue;
            if(dp[v.ind] > cost + v.cost)
            {
                dp[v.ind] = cost + v.cost;
                q.insert(make_pair(dp[v.ind], v.ind));
            }
        }
    }
}

void afisare()
{
    ofstream out("dijkstra.out");
    for(int i = 2; i <= n; ++i)
    {
        if(dp[i] == INF)
            out << 0 << " ";
        else
            out << dp[i] << " ";
    }
    out.close();
}

int main()
{
    citire();
    rezolvare();
    afisare();
    return 0;
}