Cod sursa(job #2926517)

Utilizator BuzdiBuzdugan Rares Andrei Buzdi Data 17 octombrie 2022 21:45:01
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb

#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <cstring>
#include <bitset>
 
//#include <bits/stdc++.h>
 
#define ll long long
#define ull unsigned long long
#define MOD 
#define NMAX 50001
#define KMAX 105
#define LIM 1000
#define INF 1e9
#define LOG 17
 
using namespace std;
 
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
 
struct PerechePQ
{
    int unu, doi;
    bool operator<(PerechePQ x) const
    {
        return doi < x.doi;
    }
};
 
int n, m;
vector<pair<int, int>> G[NMAX];
vector<int> Cost(NMAX, INF);
bool Proccesed[NMAX];
priority_queue<PerechePQ> pq;
 
void Djkstra()
{
    while (!pq.empty())
    {
        PerechePQ Cur = pq.top();
 
        int Node = Cur.unu, CostCur = Cur.doi;
        Proccesed[Node] = 1;
 
        for (auto Edge : G[Node])
        {
            if (!Proccesed[Edge.first])
            {
                int NewDist = Cost[Node] + Edge.second;
                if (NewDist < Cost[Edge.first])
                {
                    Cost[Edge.first] = NewDist;
                    pq.push({ Edge.first, NewDist });
                }
            }
        }
 
        pq.pop();
    }
}
 
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
 
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        G[x].push_back({ y, c });
    }
 
    Cost[1] = 0;
    pq.push({ 1, 0 });
 
    Djkstra();
 
    for (int i = 2; i <= n; i++)
        cout << Cost[i] << ' ';
 
    return 0;
}