Cod sursa(job #3253383)

Utilizator Mihai_999Diaconeasa Mihai Mihai_999 Data 2 noiembrie 2024 13:41:17
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <random>
#include <chrono>
#define nl '\n'

using namespace std;

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

const int NMAX = 50005, INF = 1e9;

int n, m, dMin[NMAX], inQ[NMAX];
vector<pair<int,int>> adj[NMAX];
queue<int> q;
struct edge
{
    int u, v, w;
};
vector<edge> muchii;

random_device rd;
mt19937 rng(rd());

int myrand()
{
    return rng() % (m-1);
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= n; i++)
        dMin[i] = INF;
    for (int i = 1; i <= m; i++)
    {
        int u, v, w;
        fin >> u >> v >> w;
        muchii.push_back({u, v, w});
    }
    unsigned seed = chrono::system_clock::now().time_since_epoch().count();
    shuffle (muchii.begin(), muchii.end(), default_random_engine(seed));
    for (int i = 0; i < m; i++)
        adj[muchii[i].u].push_back({muchii[i].v, muchii[i].w});
    ///Bellman-Ford
    dMin[1] = 0;
    inQ[1] = 1;
    q.push(1);
    while (!q.empty())
    {
        int v = q.front();
        q.pop();
        inQ[v] = 0;
        for (pair<int,int>& edge : adj[v])
        {
            int to = edge.first;
            int len = edge.second;
            if (dMin[v]+len < dMin[to])
            {
                dMin[to] = dMin[v]+len;
                if (!inQ[to])
                {
                    q.push(to);
                    inQ[to] = 1;
                }
            }
        }
    }
    for (int i = 2; i <= n; i++)
    {
        if (dMin[i] == INF)
            dMin[i] = 0;
        fout << dMin[i] << ' ';
    }
    return 0;
}