Cod sursa(job #3270606)

Utilizator tudorbuhniaTudor Buhnia tudorbuhnia Data 23 ianuarie 2025 19:55:17
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <queue>

using namespace std;

vector<pair<int,int>> G[50005];
queue<pair<int,int>> q;

int dist[50005];

void dfs()
{
    for(int i=2;i<=50000;i++)
        dist[i] = INT_MAX;

    q.push(make_pair(1,0));

    while(!q.empty())
    {
        int nod, d;
        nod = q.front().first;
        d = q.front().second;
        q.pop();

        for(auto x:G[nod])
        {
            int newdist = dist[nod] + x.second;
            if(newdist < dist[x.first])
            {
                dist[x.first] = newdist;
                q.push(make_pair(x.first, newdist));
            }
        }
    }
}

int main()
{
    ifstream cin("dijkstra.in");
    ofstream cout("dijkstra.out");

    int n, m, x, y, d;
    cin >> n >> m;
    for(int i=0;i<m;i++)
    {
        cin >> x >> y >> d;
        G[x].push_back(make_pair(y,d));
    }

    dfs();

    for(int i=2;i<=n;i++)
    {
        if(dist[i] == INT_MAX)
            cout << "0 ";
        else
            cout << dist[i] << " ";
    }
    return 0;
}