Cod sursa(job #1197560)

Utilizator xtreme77Patrick Sava xtreme77 Data 12 iunie 2014 18:14:02
Problema Algoritmul lui Dijkstra Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>

using namespace std;

#define IN  "dijkstra.in"
#define OUT "dijkstra.out"
#define rint register int
#define pb push_back
#define mp make_pair
#define s second
#define f first

const int MAX = 50014;
const int INF = 1<<30;
typedef pair<int,int> P;
vector <P> gr[MAX];
int d[MAX];
struct cmp{
    bool operator()(int n1,int n2)
    {
        if(d[n1]>d[n2])return true;
        return false;
    }
};
priority_queue <int,vector<int>,cmp> h;
void dijkstra (int nod);
int main()
{
    int n,e;
    freopen(IN, "r", stdin);
    freopen(OUT, "w", stdout);
    scanf("%d%d", &n, &e);
    while(e--){
        int x,y,cost;
        scanf("%d%d%d", &x ,&y ,&cost);
        gr[x].pb(mp(y,cost));
    }
    for(rint i=2;i<=n;d[i]=INF,h.push(i),++i);
    dijkstra(1);
    for(rint i=2;i<=n;++i)printf("%d ",(d[i]==INF)?0:d[i]);
    return 0;
}
void dijkstra (int nod){
    h.push(1);
    d[1]=0;
    while(!h.empty()){
        int fata=h.top();
        h.pop();
        for(rint i=0;i<(int)gr[fata].size();++i)
        if(d[fata]+gr[fata][i].s<d[gr[fata][i].f]){
            d[gr[fata][i].f]=d[fata]+gr[fata][i].s;
            int aux=h.top();
            h.pop();
            h.push(aux);
        }
    }
}