Cod sursa(job #2564836)

Utilizator Fatu_SamuelFatu Samuel Fatu_Samuel Data 2 martie 2020 10:39:25
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 50005, inf = 1<<30;

bitset < nmax > viz;

int n, m;

int dist[nmax];

struct vec {
    int t, c;
};

vector < vec > l[nmax];

struct comp {
    bool operator()(int a, int b)
    {
        return dist[a] > dist[b];
    }
};

priority_queue < int, vector < int >, comp > q;

void Dijkstra(int nod)
{
    viz[nod] = 1;
    q.push(nod);

    while (!q.empty())
    {
        nod = q.top();
        q.pop();
        viz[nod] = 0;

        for (vec next : l[nod])
        {
            int t = next.t, c = next.c;

            if (dist[nod] + c < dist[t])
            {
                dist[t] = dist[nod] + c;

                if (!viz[t])
                    q.push(t);

                viz[t] = 1;
            }
        }
    }
}

int main()
{
    fin >> n >> m;


    for (int i = 1; i <= m; i++)
    {
        int f, t, c;

        fin >> f >> t >> c;

        l[f].push_back({t, c});
        l[t].push_back({f, c});
    }

    for (int i = 2; i <= n; i++)
        dist[i] = inf;

    dist[1] = 0;

    Dijkstra(1);

    for (int i = 2; i <= n; i++)
    {
        if (dist[i] == inf)
            dist[i] = 0;

        fout << dist[i] << ' ';
    }

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