Cod sursa(job #2915832)

Utilizator andreipirjol5Andrei Pirjol andreipirjol5 Data 25 iulie 2022 12:56:06
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;
FILE *fin, *fout;

#define NMAX 50000
struct edge
{
    int dest, cost;
};

vector <edge> graph[NMAX + 5];

struct cmp
{
    bool operator()(edge e1, edge e2)
    {
        if(e1.cost > e2.cost)
            return true;

        return false;
    }
};
priority_queue <edge, vector <edge>, cmp> pq;

int d[NMAX + 5];

void dij(int source)
{
    d[source] = 0;
    edge e;
    e.dest = source;
    e.cost = 0;
    pq.push(e);

    while(!pq.empty())
    {
        e = pq.top();
        pq.pop();

        if(e.cost > d[e.dest])
            continue;

        for(auto neigh : graph[e.dest])
        {
            if(d[neigh.dest] == -1 or d[neigh.dest] > d[e.dest] + neigh.cost)
            {
                d[neigh.dest] = d[e.dest] + neigh.cost;

                edge new_edge;
                new_edge.dest = neigh.dest;
                new_edge.cost = d[neigh.dest];

                pq.push(new_edge);
            }
        }
    }
}

int main()
{
    fin = fopen("dijkstra.in", "r");
    fout = fopen("dijkstra.out", "w");

    int n, m;
    fscanf(fin, "%d%d", &n, &m);

    int i, u, v, cost;
    edge e;

    for(i = 0; i < m; i++)
    {
        fscanf(fin, "%d%d%d", &u, &v, &cost);

        e.dest = v;
        e.cost = cost;
        graph[u].push_back(e);

        pq.push(e);
    }

    for(i = 1; i <= n; i++)
        d[i] = -1;

    dij(1);

    for(i = 2; i <= n; i++)
    {
        if(d[i] == -1)
            d[i] = 0;
        fprintf(fout, "%d ", d[i]);
    }

    fclose(fin);
    fclose(fout);
    return 0;
}