Cod sursa(job #3270283)

Utilizator Alexbora13Bora Ioan Alexandru Alexbora13 Data 22 ianuarie 2025 19:25:47
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 50000;

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

int n, m, x, y, cost;
vector < pair<int,int> > v[NMAX+1];
int dist[NMAX+1];

void dijkstra()
{
    set < pair<int,int> > st;
    st.insert(make_pair(0,1));
    dist[1] = 0;
    while(!st.empty())
    {
        auto tp = make_pair(st.begin() -> first, st.begin() -> second);
        st.erase(st.begin());
        for(auto a : v[tp.second])
        {
            if(dist[a.first] > tp.first + a.second)
            {
                st.erase(make_pair(dist[a.first], a.first));
                dist[a.first] = tp.first + a.second;
                st.insert(make_pair(tp.first+a.second, a.first));
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        fin >> x >> y >> cost;
        v[x].push_back( make_pair(y,cost) );
    }
    for(int i=1; i<=n; i++)
        dist[i] = INT_MAX;
    dijkstra();
    for(int i=2; i<=n; i++)
        if(dist[i] == INT_MAX)
            fout << -1 << ' ';
        else
            fout << dist[i] << ' ';
    return 0;
}