Cod sursa(job #1892149)

Utilizator gabrielamoldovanMoldovan Gabriela gabrielamoldovan Data 24 februarie 2017 19:06:28
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

#define nmax 50010
#define inf 100000

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

vector < vector < pair <int, int> > >G(nmax);
priority_queue < pair <int, int> > PQ;
int n;
int dist[nmax], viz[nmax];

void citire()
{
    int m, a, b, c;
    f>>n>>m;
    while(m--)
    {
        f>>a>>b>>c;
        G[a].push_back(make_pair(b,c));
    }
}

void init()
{
    dist[1]=0;
    for(int i=2; i<=n; ++i)
    {
        dist[i]=inf;
    }
}

void rezolvare()
{
    PQ.push(make_pair(0, 1));
    while(PQ.size())
    {
        pair <int, int> aux;
        aux=PQ.top();
        PQ.pop();
        int nod=aux.second;
        if(viz[nod])
        {
            continue;
        }
        viz[nod]=1;
        for(int i=0; i<G[nod].size(); ++i)
        {
            int suma=dist[nod]+G[nod][i].second;
            if(suma<dist[G[nod][i].first])
            {
                dist[G[nod][i].first] =suma;
                PQ.push(make_pair(-dist[G[nod][i].first], G[nod][i].first));
            }
        }
    }
    for(int i=2; i<=n; ++i)
    {
        if(dist[i]==inf)
        {
            dist[i]=0;
        }
        g<<dist[i]<<" ";
    }
}

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