Cod sursa(job #2805839)

Utilizator namesurname01Name Surname namesurname01 Data 22 noiembrie 2021 02:29:08
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <cstdio>
#define N 50002
#define INF 2000000000
#include <vector>
#include <queue>

using namespace std;
FILE* f, * g;

struct bla
{
    int ve, co;
};
vector <bla> graph[N];
bool viz[N];
int d[N];
struct cmp
{
    bool operator ()(int A, int B)
    {
        return (d[A] > d[B]);
    }
};
priority_queue <int, vector <int>, cmp> q;

void dijkstra(int nod)
{
    d[nod] = 0;
    q.push({ nod });
    while (!q.empty())
    {
        nod = q.top();
        q.pop();
        if (!viz[nod])
        {
            for (int i = 0;i < graph[nod].size();++i)
                if (d[graph[nod][i].ve] > d[nod] + graph[nod][i].co)
                {
                    d[graph[nod][i].ve] = d[nod] + graph[nod][i].co;
                    q.push({ graph[nod][i].ve });
                }
            viz[nod] = 1;
        }
    }
}
int main()
{
    f = fopen("dijkstra.in", "r");
    g = fopen("dijkstra.out", "w");
    int n, m;
    fscanf(f, "%d %d", &n, &m);
    int x, y, z;
    for (int i = 1;i <= m;++i)
    {
        fscanf(f, "%d %d %d", &x, &y, &z);
        graph[x].push_back({ y,z });
    }
    for (int i = 1;i <= n;++i)
        d[i] = INF;
    dijkstra(1);
    for (int i = 2;i <= n;++i)
        if (d[i] == INF)
            fprintf(g, "0 ");
        else
            fprintf(g, "%d ", d[i]);
    return 0;
}