Cod sursa(job #1036312)

Utilizator DemnokStefan Demnok Data 19 noiembrie 2013 10:34:14
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include<cstdio>
#include<vector>
#include<queue>
#include<utility>
#include<fstream>
#define NMAX 50001
#define INF 2500010
using namespace std;

int n, m, D[NMAX];
vector<pair<int, int> > B[NMAX];
priority_queue <pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > H;
void Citeste()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    int i, x, y, c;
    scanf("%ld%ld",&n,&m);
    for (i=1; i<=m; ++i)
    {
        scanf("%ld%ld%ld",&x,&y,&c);
        B[x].push_back(make_pair(c, y));
    }
     D[1]=0;
    for (i=2; i<=n; ++i) D[i]=INF;
}
void Dijkstra()
{
    pair<int, int> pr;
    int z,lg;

    H.push(make_pair(0, 1));
    while (!H.empty())
    {
        int i,j;
        pr=H.top(); H.pop();
        i=pr.second;
        for(j=0;j<B[i].size();j++)
            {
                z=B[i][j].second;;
                lg=D[i]+B[i][j].first;
                if(lg<D[z])
                {
                    H.push(make_pair(lg,z));
                    D[z]=lg;
                }
            }
     }
}
void Scrie()
{
    int i;
    for (i=2; i<=n; ++i)
        if (D[i]==INF) printf("0 ");
            else printf("%ld ",D[i]);
}
int main()
{
    Citeste();
    Dijkstra();
    Scrie();
   return 0;
}