Cod sursa(job #3296342)

Utilizator Radu_VasileRadu Vasile Radu_Vasile Data 12 mai 2025 12:08:52
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <bits/stdc++.h>

const int MAXN = 50'000;
const int MAXM = 250'000;
const int BUFSIZE = (65'536);
const int INF = 2'000'000'000;
int head[MAXM + 1];
const int NIL = -1;
int n, m;
struct Edge{
  int u, cost;
  bool operator <(const Edge &a) const {
    return cost > a.cost;
  }
};
int nl = 0;
struct List{
  int nxt;
  Edge e;
}list[MAXM + 1];
void addEdge(int u, int v, int w) {
  list[nl] = {head[u], {v, w}};
  head[u] = nl++;
}
class InParser {
private:
	FILE * fin;
	char * buff;
	int sp;

	char read_ch() {
		if(!(sp = (sp + 1) & (BUFSIZE - 1))) {
			fread(buff, 1, BUFSIZE, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char * nume) {
		fin = fopen(nume, "r");
		buff = new char[BUFSIZE]();
		sp = 1823;
	}

	InParser& operator >> (int &n) {
		char c;
		while(!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if(c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while(isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while(!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if(c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while(isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};

InParser fin("dijkstra.in");
std::ofstream fout("dijkstra.out");
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(int y = head[e.u]; y != NIL; y = list[y].nxt) {
        Edge nxt = list[y].e;
        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++ ) {
    if(dist[i] == INF)
      dist[i] = 0;
    fout << dist[i] << " ";
  }
}
int main(){
  fin >> n >> m;
  for( int i = 1; i <= m; i++ ) {
    head[i] = NIL;
  }
  for( int i = 0; i < m; i++ ) {
    int u, v, w;
    fin >> u >> v >> w;
    addEdge(u, v, w);
  }
  dijkstra(1);
  return 0;
}