Cod sursa(job #1460928)

Utilizator BaweeLazar Vlad Bawee Data 14 iulie 2015 12:58:01
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <cstdio>
#include <vector>
#include <set>

#define Dim 50001
#define INF 1000000

using namespace std;

int n,m,d[Dim];
vector< pair<int,int> > G[Dim];
set < pair <int,int> > S;

void dijkstra()
{
    for(int i = 2; i <= n; i++)
        d[i] = INF;

    S.insert(make_pair(0,1));
    while(!S.empty())
    {
        int Dist = (*S.begin()).first;
        int Ind = (*S.begin()).second;
        S.erase(*S.begin());
        for(int i = 0; i < G[Ind].size(); i++)
        {
            if(d[G[Ind][i].first] > Dist + G[Ind][i].second)
            {
                d[G[Ind][i].first] = Dist + G[Ind][i].second;
                S.insert(make_pair(d[G[Ind][i].first],G[Ind][i].first));
            }
        }
    }
}

int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);

    scanf("%d%d",&n,&m);

    int a,b,c;
    for(int i = 1; i <= m; i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        G[a].push_back(make_pair(b,c));
    }

    dijkstra();

    for(int i = 2; i <= n; i++)
    {
        printf("%d ",d[i] == INF ? 0 : d[i]);
    }
    return 0;
}