Cod sursa(job #2297256)

Utilizator andrei_diaconu11Andrei C. Diaconu andrei_diaconu11 Data 5 decembrie 2018 17:03:37
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int lim = 5e4, INF = 2e9;

struct nod{
  int x, cost;
};

bool operator <(const nod a, const nod b){
  if(a.cost == b.cost)
    return a.x < b.x;
  return a.cost > b.cost;
}

priority_queue <nod> q;
vector <nod> ad[lim + 1];
int dist[lim + 1];
bool viz[lim + 1];

inline void dijkstra(int start, int n){
  q.push({start, 0});
  for(int i = 1; i <= n; i++)
    if(i != start)
      dist[i] = INF;
  while(q.size() > 0){
    nod poz = q.top();
    q.pop();
    if(!viz[poz.x]){
      viz[poz.x] = true;
      dist[poz.x] = poz.cost;
      for(auto fiu : ad[poz.x])
        if(!viz[fiu.x] && fiu.cost + poz.cost < dist[fiu.x]){
          q.push({fiu.x, fiu.cost + poz.cost});
          dist[fiu.x] = fiu.cost + poz.cost;
        }
    }
  }
}

int main()
{
  int n, m, x, y, c;
  fin >> n >> m;
  for(int i = 0; i < m; i++){
    fin >> x >> y >> c;
    ad[x].push_back({y, c});
  }
  dijkstra(1, n);
  for(int i = 2; i <= n; i++){
    if(dist[i] == INF)
      fout << "0 ";
    else
      fout << dist[i] << ' ';
  }
  fin.close();
  fout.close();
  return 0;
}