Cod sursa(job #2854682)

Utilizator TiberiwTiberiu Amarie Tiberiw Data 21 februarie 2022 17:32:27
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#define Dmax 50005
#define inf 0x3F3F3F3F
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int n,m,D[Dmax];
vector<pair<int,int> >G[Dmax];
bool viz[Dmax];
priority_queue<pair<int,int>, vector<pair<int,int> >, greater< pair<int,int> > > Q;

void Dijkstra(int start)
{
    for(int i = 1; i <= n; i++)
        D[i] = inf;

    D[start] = 0;
    Q.push({0,start});
    while(!Q.empty())
    {
        int x = Q.top().first;
        int y = Q.top().second;
        Q.pop();
        if(x > D[y])
            continue;
        for(vector<pair<int,int > >::iterator it = G[y].begin(); it < G[y].end(); it++)
        {
            int Vecin = it->first;
            int Cost = it->second;
            if(D[Vecin] > D[y] + Cost)
            {
                D[Vecin] = D[y] + Cost;
                Q.push({D[Vecin],Vecin});
            }
        }
    }




}



int main()
{
    f>>n>>m;
    for(int i = 1; i <= m; i++)
    {
        int x,y,z;
        f>>x>>y>>z;
        G[x].push_back({y,z});
    }

    Dijkstra(1);
    for(int i = 2; i <= n; i++)
        if(D[i]==inf)
        g<<"0 ";
        else
            g<<D[i]<<" ";

    return 0;
}