Pagini recente » Cod sursa (job #1759082) | Cod sursa (job #2510457) | Cod sursa (job #66350) | Cod sursa (job #983027) | Cod sursa (job #3166823)
#include <fstream>
#include <vector>
#include <climits>
#include <utility>
#include <queue>
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
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");
const int INF = INT_MAX;
struct Min {
int nod, cost;
};
struct compare {
bool operator () (Min & a, Min & b) {
return a.cost < b.cost;
}
};
int main () {
int n, m; fin >> n >> m;
std::vector<int> dist(n, INF);
std::priority_queue<Min, std::vector<Min>, compare> heap;
std::vector<std::vector<Min>> graph(n, std::vector<Min> ());
while (m > 0) {
int u, v, c; fin >> u >> v >> c; u -= 1, v -= 1;
graph[u].emplace_back (Min {v, c});
m -= 1;
}
dist[0] = 0;
heap.push (Min {0, 0});
while (!heap.empty ()) {
int intermediary = heap.top().nod;
int distance = heap.top ().cost;
heap.pop ();
for (int i = 0; i < (int) graph[intermediary].size (); i += 1) {
int nod = graph[intermediary][i].nod;
int Dist = graph[intermediary][i].cost;
if (dist[nod] > dist[intermediary] + Dist) {
dist[nod] = dist[intermediary] + Dist;
heap.push (Min {nod, dist[nod]});
}
}
}
for (int i = 1; i < (int) dist.size (); i += 1)
fout << (dist[i] != INF ? dist[i] : 0) << ' ';
return 0;
}