Cod sursa(job #3273638)

Utilizator Mihai00700Mihai Ghetu Mihai00700 Data 2 februarie 2025 23:54:23
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <set>
#include <vector>
#define int long long
using namespace std;
const int INF = 1e18;
const int NMAX =50002; 

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
vector <pair<int, int> > adj[NMAX + 2];
int v[NMAX + 2];
int n, source, m;
void dijkstra(){

  vector <bool> visited(n, false);
  for(int i = 2;i<=n;i++){
    v[i] = INF;
  }
  for(int i = 1;i<=n;i++){
    int nod = INF;
    int pmin = 0;
    for(int j= 1;j<=n;j++){
      if(!visited[j] && v[j] < nod){
        nod = v[j];
        pmin = j;
      }
    }
    nod = pmin;
    visited[nod] = true;
    for(auto vecin : adj[nod]){
      int to = vecin.first;
      int cost = vecin.second;
      if(v[nod] + cost < v[to]){
        v[to] = v[nod] + cost;
      }
    }
  }
  for(int i = 2;i<=n;i++){
    if(v[i] == INF){
      out<<"0 ";
    }else{
      out<<v[i]<<" ";
    }
  }
}
signed main(){
  int from, to, cost;
  in>>n>>m;
  source = 1;
  for(int i = 1;i<=m;i++){
    in>>from>>to>>cost;
    adj[from].push_back(make_pair(to, cost));
  }
  dijkstra();
  return 0;
}