Cod sursa(job #3296264)

Utilizator Radu_VasileRadu Vasile Radu_Vasile Data 12 mai 2025 11:33:54
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>
const int MAXN = 50'000;
const int BUFSIZE = (4 * 131'072);
const int INF = 2'000'000'000;
int n, m;
struct Edge{
  int u, cost;
  bool operator <(const Edge &a) const {
    return cost > a.cost;
  }
};
std::vector<Edge> adj[MAXN + 1];

FILE *fin, *fout;
void openFiles() {
  fin = fopen("dijkstra.in", "r");
  fout = fopen("dijkstra.out", "w");
}
void closeFiles() {
  fclose(fin);
  fclose(fout);
}
char rbuf[BUFSIZE];
int rpos = BUFSIZE - 1;
char readChar() {
  rpos = (rpos + 1) % BUFSIZE;
  if(rpos == 0)
    fread(rbuf, 1, BUFSIZE, fin);
  return rbuf[rpos];
}
int readInt() {
  char ch;
  while(!isdigit(ch = readChar()));
  int nr = 0;
  do{
    nr = nr * 10 + ch - '0';
  }while(isdigit(ch = readChar()));
  return nr;
}
int dist[MAXN + 1];
void dijkstra(int node) {
  std::priority_queue<Edge> pq;
  pq.push({node, 0});
  for( int i = 1; i <= n; i++ )
    dist[i] = INF;
  dist[0] = 1;
  dist[node] = 0;
  while(!pq.empty()) {
    Edge e = pq.top();
    pq.pop();
    if(e.cost == dist[e.u]) {
      for( Edge nxt : adj[e.u] ) {
        int newdist = nxt.cost + dist[e.u];
        int newnode = nxt.u;
        if(newdist < dist[nxt.u]) {
          pq.push({newnode, newdist});
          dist[nxt.u] = newdist;
        }
      }
    }
  }

  for( int i = 2; i <= n; i++ ) {
    fprintf(fout, "%d ", dist[i] == INF ? 0 : dist[i]);
  }
}
int main(){
  openFiles();
  n = readInt();
  m = readInt();
  for( int i = 0; i < m; i++ ) {
    int u, v, w;
    u = readInt();
    v = readInt();
    w = readInt();
    adj[u].push_back({v, w});
  }
  dijkstra(1);
  closeFiles();
  return 0;
}