Cod sursa(job #3296266)

Utilizator RaresHRares Hanganu RaresH Data 12 mai 2025 11:35:29
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
#include <fstream>
#include <queue>
#include <vector>

const int MAX_N = 50'000;
const int INF = 2'000'000'000;

class InParser {
private:
	FILE * fin;
	char * buff;
	int sp;

	char read_ch() {
		++sp;
		if(sp == 16384) {
			sp = 0;
			fread(buff, 1, 16384, fin);
		}
		return buff[sp];
	}

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

	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");

struct Edge {
  int node;
  int cost;
};

struct State {
  int node;
  int cost;

  bool operator<(const State &other) const {
    return cost > other.cost;
  }
};

int n;
std::vector<Edge> adj[MAX_N];
int min_cost[MAX_N];

void dijkstra(int source) {
  for(int i = 0; i < n; i++) {
    min_cost[i] = INF;
  }

  std::priority_queue<State> pq;
  min_cost[source] = 0;
  pq.push({source, 0});
  while(!pq.empty()) {
    State nd = pq.top();
    pq.pop();
    if(nd.cost == min_cost[nd.node]) {
      for(Edge &e : adj[nd.node]) {
        int c = nd.cost + e.cost;
        if(c < min_cost[e.node]) {
          min_cost[e.node] = c;
          pq.push({e.node, c});
        }
      }
    }
  }
}

int main() {
  int m;
  fin >> n >> m;
  for(int i = 0; i < m; i++) {
    int u, v, cost;
    fin >> u >> v >> cost;
    u--;
    v--;
    adj[u].push_back({v, cost});
  }

  dijkstra(0);

  for(int i = 1; i < n; i++) {
    fout << (min_cost[i] == INF ? 0 : min_cost[i]) << " ";
  }
  fout << "\n";

  return 0;
}