Cod sursa(job #1658733)

Utilizator sorynsooSorin Soo sorynsoo Data 21 martie 2016 19:21:41
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
#define MAXN 50005
#define INF 0x3f3f3f3f

struct rct
{
    int nod,cost;
}act,aux;

class comp{
public:
    bool operator() (rct A, rct B)
    {
        return A.cost > B.cost;
    }
};

vector<rct> graf[MAXN];
priority_queue<rct, vector<rct>, comp> coada;
int d[MAXN];
int n,m,i,j,x,y,z;

int main()
{
    cin>>n>>m;
    for(i=1; i<=m; i++)
    {
        cin>>x>>y>>z;
        act.nod=y; act.cost=z;
        graf[x].push_back(act);
    }
    for(i=2; i<=n; i++)
        d[i]=INF;

    act.nod=1; act.cost=0;
    coada.push(act);
    while(!coada.empty())
    {
        act=coada.top(); coada.pop();
        if(act.cost != d[ act.nod ])
            continue;

        for(i=0; i<graf[act.nod].size(); i++)
        {
            if(d[ graf[act.nod][i].nod ] > d[act.nod] + graf[act.nod][i].cost)
            {
                d[ graf[act.nod][i].nod ] = d[act.nod] + graf[act.nod][i].cost;
                aux.nod = graf[act.nod][i].nod;
                aux.cost = d[ graf[act.nod][i].nod ];
                coada.push(aux);
            }
        }
    }
    for(i=2; i<=n; i++)
        if(d[i] == INF)
            cout<<0<<" ";
        else
            cout<<d[i]<<" ";
    return 0;
}