Cod sursa(job #2945407)

Utilizator acostin643costin andrei acostin643 Data 23 noiembrie 2022 19:17:15
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <vector>
#include <limits.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int NMAX = 50000;

int N, M;
int a, b, c;
bool visited[NMAX + 5];
bool enqueued[NMAX + 5];
vector <int> v[NMAX + 5];
vector <int> g[NMAX + 5];
int shortest[NMAX + 5];
int pq[NMAX + 5], in = 0;

void enqueue(int x)
{
    in++;
    pq[in] = x;
    while(shortest[pq[in]] < shortest[pq[in - 1]] && in - 1 >= 1)
        swap(pq[in], pq[in - 1]);
}

void dequeue()
{
    in--;
    for(int i = 1; i <= in; i++)
        pq[i] = pq[i + 1];
}

void dijkstra(int src, int curr_length)
{
    for(int i = 0; i < g[src].size(); i++)
    {
        if(!visited[g[src][i]])
        {
            if(curr_length + v[src][i] < shortest[g[src][i]])
            {
                shortest[g[src][i]] = curr_length + v[src][i];
            }
            if(!enqueued[g[src][i]])
            {
                enqueue(g[src][i]);
                enqueued[g[src][i]] = 1;
            }
        }
    }
}

int main()
{
    fin >> N >> M;
    for(int i = 1; i <= N; i++)
    {
        shortest[i] = INT_MAX;
    }
    for(int i = 1; i <= M; i++)
    {
        fin >> a >> b >> c;
        g[a].push_back(b);
        g[b].push_back(a);
        v[a].push_back(c);
        v[b].push_back(c);
    }



    enqueue(1);
    shortest[1] = 0;
    enqueued[1] = 1;


    while(in)
    {
        visited[pq[1]] = 1;
        dijkstra(pq[1], shortest[pq[1]]);
        dequeue();
    }


    for(int i = 2; i <= N; i++)
    {
        if(shortest[i] ==  INT_MAX)
            fout << "0 ";
        else
            fout << shortest[i] << " ";
    }


    fin.close();
    fout.close();
    return 0;
}