Cod sursa(job #2567904)

Utilizator Anastasia11Susciuc Anastasia Anastasia11 Data 3 martie 2020 19:37:55
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define Nmax 50005
#define INF 0x3f3f3f3f

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int n, m;
vector < pair <int, int> > v[Nmax];
int d[Nmax];
bool in[Nmax];
struct cmp{
    bool operator()(int a, int b)
    {
        return d[a]>d[b];
    }

};
priority_queue <int, vector <int>, cmp> Q;

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

    memset(d, INF, sizeof(d));
    d[1]=0;
    Q.push(1);
    in[1]=1;
    while (!Q.empty())
    {
        int x=Q.top();
        Q.pop();
        in[x]=0;
        for (auto i:v[x])
        {
            int y=i.first, c=i.second;

            if (d[y] > d[x]+c)
            {
                d[y]=d[x]+c;
                if (in[y] == 0)
                {
                    Q.push(y);
                    in[y]=1;
                }
            }

        }
    }

    for (int i = 2; i <= n; i++)
        if (d[i]==INF) g << "0 ";
        else g << d[i] << ' ';


    return 0;
}