Cod sursa(job #2901762)

Utilizator iraresmihaiiordache rares mihai iraresmihai Data 14 mai 2022 13:24:59
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <queue>
#include <vector>

#define MAXN 50000
#define INF 1000000000

using namespace std;

struct edge{
  int b, cost;
};

inline bool operator< (edge a, edge b) {
  return a.cost < b.cost;
}

queue <edge> q;
vector <edge> graph[MAXN];
int minDist[MAXN];

void addEdge(int a, int b, int cost) {
  graph[a].push_back({b, cost});
  graph[b].push_back({a, cost});
}

void dijkstra(int n) {
  int i, node;

  for ( i = 1; i < n; i++ ) {
    minDist[i] = INF;
  }

  minDist[0] = 0;
  for ( edge x : graph[0] ) {
    q.push({x.b, x.cost});
  }

  while ( q.size() ) {
    if ( minDist[q.front().b] > q.front().cost ) {
      minDist[q.front().b] = q.front().cost;
      node = q.front().b;
      q.pop();

      for ( edge x : graph[node] ) {
        if ( minDist[x.b] > minDist[node] + x.cost ) {
          minDist[x.b] = minDist[node] + x.cost;
          q.push({x.b, minDist[node] + x.cost});
        }
      }
    } else {
      q.pop();
    }
  }
}

int main() {
  FILE *fin, *fout;
  fin = fopen("dijkstra.in", "r");
  fout = fopen("dijkstra.out", "w");

  int n, m, i, a, b, c;

  fscanf(fin, "%d%d", &n, &m);

  for ( i = 0; i < m; i++) {
    fscanf(fin, "%d%d%d", &a, &b, &c);

    addEdge(a - 1, b - 1, c);
  }

  dijkstra(n);

  for ( i = 1; i < n; i++ ) {
    fprintf(fout, "%d ", minDist[i]);
  }

  fclose(fin);
  fclose(fout);

  return 0;
}