Cod sursa(job #2073697)

Utilizator ApostolIlieDanielApostol Daniel ApostolIlieDaniel Data 23 noiembrie 2017 16:09:31
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

using namespace std;
const int MAXM = 25e4;
const int INF = 1e9 + 20;
int n;

vector < pair < int, int > > G[MAXM];
priority_queue <pair <int,int>, vector < pair <int,int> > ,greater <pair <int,int> > > heap;
int dist[MAXM];
void dijkstra (int start) {
  int son, cost, node, distson, i;
  for (i = 1; i <= n; i++) {
    dist[i] = INF;
  }
  heap.push ({0, start});
  while (heap.empty() != 0) {
    node = heap.top().second;
    cost = heap.top().first;
    heap.pop();
    if (cost <= dist[node]) {
      for (i = 0; i < G[node].size(); i++) {
        son = G[node][i].first;
        distson = G[node][i].second;
        if (dist[son] > cost + distson) {
          dist[son] = cost + distson;
          heap.push ({distson, son});
        }
      }
    }
  }
}

int main()
{
  FILE *fin, *fout;
  int m, i, x, y, cost;
  fin = fopen ("djikstra.in", "r");
  fout = fopen ("djikstra.out", "w");
  fscanf (fin, "%d%d", &n, &m);
  for (i = 0; i < m; i++) {
    fscanf (fin, "%d%d%d", &x, &y, &cost);
    G[x].push_back((make_pair (y, cost)));
  }
  dijkstra(1);
  for (i = 2; i <= n; i++){
    if (dist[i] != 1000000000)
      fprintf (fout, "%d ", dist[i]);
    else
      fprintf (fout, "0 ");
  }
  fclose (fin);
  fclose (fout);
  return 0;
}