Cod sursa(job #2806605)

Utilizator AndreeaGeamanuAndreea AndreeaGeamanu Data 22 noiembrie 2021 20:31:19
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb

#include <iostream>
#include <fstream>
#include <bits/stdc++.h>

#define nmax 50050
const int inf = 0x3f3f3f3f;

using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

vector <pair<int,int>> la[nmax];
int tata[nmax]={0}, d[nmax];
priority_queue <pair<int,int>> pq;



int main()
{   int n,m,x,y,c;
    f>>n>>m;

    // Se introduc perechile (nod, cost) in liste de adiacenta
    for(int i=1; i<=m; i++){
        f>>x>>y>>c;
        la[x].push_back(make_pair(y,c));
        la[y].push_back(make_pair(x,c));
    }

    memset(d, inf, sizeof(d));
    d[1]=0;

    for(int j=1; j<=n; j++){
        pq.push(make_pair(-d[j], j));
    }

    while(!pq.empty()){
        pair<int,int> top=pq.top();
        pq.pop();
        for(int k=0; k<la[top.second].size(); k++){
            if(d[top.second]+la[top.second][k].second< d[la[top.second][k].first]){
                d[la[top.second][k].first] = d[top.second]+la[top.second][k].second;
                tata[la[top.second][k].first]=top.second;
            }
        }
    }

    for(int l=2; l<=n; l++){
        if(d[l]==inf) g<<0<<" ";
        else g<<d[l]<<" ";
    }

    f.close();
    g.close();
    return 0;
}