Cod sursa(job #2796900)

Utilizator mirelPmirel p mirelP Data 8 noiembrie 2021 23:21:38
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
	
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define pf push_front
#define MOD 1000000007
#define NMAX 50005
 
using namespace std;
 
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 
struct A
{
    int y, cost;
};
 
vector < A > v[NMAX];
queue < int > q;
 
int main()
{
    ios_base::sync_with_stdio(false), cin.tie(0),cout.tie(0);
    int n, m, x, y, z, i, nr[NMAX], r[NMAX];
    bool fr[NMAX];
 
    fin >> n >> m;
    while(m--)
    {
        fin >> x >> y >> z;
        v[x].pb({y, z});
    }
 
    for(i = 1; i <= n; i++) fr[i] = 0, nr[i] = 0, r[i] = INT_MAX;
    r[1] = 0, fr[1] = 1, q.push(1);
    while(q.empty() == 0)
    {
        x = q.front(), q.pop();
 
        fr[x] = 0;
        nr[x]++;
        if(nr[x] == n)
        {
            fout << "Ciclu negativ!";
            break;
        }
        else for(auto it:v[x])
                if(r[x] + it.cost < r[it.y])
                {
                    r[it.y] = r[x] + it.cost;
                    if(fr[it.y] == 0) fr[it.y] = 1, q.push(it.y);
                }
    }
 
    if(nr[x] != n) for(i = 2; i <= n; i++) fout << r[i] << ' ';
 
 
    return 0;
}