Cod sursa(job #2867615)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 10 martie 2022 14:15:00
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.8 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair
#define dbg(x) cout << #x <<": " << x << "\n";
using ll = long long;

class InP {
	FILE *fin;
	char *buff;
	int sp;

public:
	InP(const char *p) {
		fin = fopen(p, "r");
		buff = new char[4096]();
		sp = 4095;
	}
	~InP() {
		fclose(fin);
	}
	char read_ch() {
		sp++;
		if (sp == 4096) {
			fread(buff, 1, 4096, fin);
			sp = 0;
		}
		return buff[sp];
	}

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

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

	InP &operator >> (char &n) {
		n = read_ch();
		while ((n = read_ch()) != '\n' && n != ' ');
		return *this;
	}

};

class OuP {
	FILE *fout;
	char *buff;
	int sp;

public:

	OuP(const char *p) {
		fout = fopen(p, "w");
		buff = new char[50000];
		sp = 0;
	}
	~OuP() {
		fwrite(buff, 1, sp, fout);
		fclose(fout);
	}
	void write_ch(char c) {
		if (sp == 50000) {
			fwrite(buff, 1, sp, fout);
			sp = 0;
		}
		buff[sp++] = c;
	}

	OuP &operator <<(int n) {
		if (n <= 9)
			write_ch(n + '0');
		else {
			*(this) << (n / 10);
			write_ch(n % 10 + '0');
		}
		return *this;
	}

	OuP &operator <<(ll n) {
		if (n <= 9)
			write_ch(n + '0');
		else {
			*(this) << (n / 10);
			write_ch(n % 10 + '0');
		}
		return *this;
	}

	OuP &operator <<(char c) {
		write_ch(c);
		return *this;
	}

	OuP &operator <<(const char *c) {
		while (*c) {
			write_ch(*c);
			c++;
		}
		return *this;
	}

};

InP fin("dijkstra.in");
OuP fout("dijkstra.out");

// ifstream fin("file.in");
// ofstream fout("file.out");

int n, m;
int d[50005];
vector<pair<int , int> > g[50005];

struct cmp
{
	bool operator()(const int &x, const int &y) {
		return d[x] > d[y];
	}
};
priority_queue<int, vector<int> , cmp > q;

void dijkstra(int nod) {
	for (int i = 1; i <= n; ++i)
		d[i] = 2e9;
	d[nod] = 0;
	q.push(nod);
	while (!q.empty()) {

		int ac = q.top();
		q.pop();
		for (auto i : g[ac]) {
			// cout << d[i.first] << " ";
			if (d[ac] + i.second < d[i.first]) {
				d[i.first] = d[ac] + i.second;
				q.push(i.first);
			}
		}
	}
}

int main() {

	fin >> n >> m;
	while (m--) {
		int x, y, w;
		fin >> x >> y >> w;
		g[x].pb({y, w});
	}
	dijkstra(1);
	for (int i = 2; i <= n; ++i)
		fout << d[i] << " ";
// fin.close();
// fout.close();
	return 0;
}