Cod sursa(job #3349121)

Utilizator andrei_obrejaAndrei Obreja andrei_obreja Data 25 martie 2026 16:39:54
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<vector<pair<int,int>>> g;
vector<int> nodfrom1;
int n,m;
void dijkstra(int start)
{
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int, int>>> q;
    q.push({0, start});
    nodfrom1[1] = 0;
    while(!q.empty())
    {
        auto u = q.top();
        int ucost = u.first;
        int unod = u.second;
        //cout << u.first <<' ' <<u.second << '\n';
        q.pop();
        for(auto v : g[unod]){

            if(nodfrom1[v.second] >= 0){
                if(nodfrom1[v.second] > v.first + nodfrom1[unod])
                    nodfrom1[v.second] = v.first + nodfrom1[unod], q.push(v);
            }

            else
            {
                nodfrom1[v.second] = v.first + nodfrom1[unod];
                q.push(v);
            }

            }
    }
}
int main()
{
    fin >> n>> m;
    nodfrom1.resize(n + 1, -1);
    g.resize(n + 1);
    for(int i = 1; i <= m; i++)
    {
        int u,v,cost;
        fin >> u >> v >> cost;
        g[u].push_back({cost, v});

    }
   // for(int i = 1; i <= n; i++)
      //  for(auto v : g[i])
            //cout << v.second <<' ' << v.first << '\n';
    dijkstra(1);
    for(int i = 2; i <= n; i++)
        fout << (nodfrom1[i] >= 0 ? nodfrom1[i] : 0) <<' ';
    return 0;
}