Pagini recente » Cod sursa (job #32560) | Cod sursa (job #333317) | Cod sursa (job #32558) | Cod sursa (job #1909590) | Cod sursa (job #3296356)
#include <fstream>
#include <queue>
const int MAX_N = 50'000;
const int INF = 2'000'000'000;
const int MAX_M = 250'000;
const int NIL = -1;
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;
}
};
class OutParser {
private:
FILE *fout;
char *buff;
int sp;
void write_ch(char ch) {
if (sp == 50000) {
fwrite(buff, 1, 50000, fout);
sp = 0;
buff[sp++] = ch;
} else {
buff[sp++] = ch;
}
}
public:
OutParser(const char* name) {
fout = fopen(name, "w");
buff = new char[50000]();
sp = 0;
}
~OutParser() {
fwrite(buff, 1, sp, fout);
fclose(fout);
}
OutParser& operator << (int vu32) {
if (vu32 <= 9) {
write_ch(vu32 + '0');
} else {
(*this) << (vu32 / 10);
write_ch(vu32 % 10 + '0');
}
return *this;
}
OutParser& operator << (long long vu64) {
if (vu64 <= 9) {
write_ch(vu64 + '0');
} else {
(*this) << (vu64 / 10);
write_ch(vu64 % 10 + '0');
}
return *this;
}
OutParser& operator << (char ch) {
write_ch(ch);
return *this;
}
OutParser& operator << (const char *ch) {
while (*ch) {
write_ch(*ch);
++ch;
}
return *this;
}
};
InParser fin("dijkstra.in");
OutParser 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;
}
};
struct ListNode {
Edge e;
int next;
};
int n;
int min_cost[MAX_N];
int head[MAX_N];
int ptr;
ListNode nodes[MAX_M];
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();
int pos = head[nd.node];
while(pos != NIL) {
Edge e = nodes[pos].e;
int c = nd.cost + e.cost;
if(c < min_cost[e.node]) {
min_cost[e.node] = c;
pq.push({e.node, c});
}
pos = nodes[pos].next;
}
}
}
void add_edge(int u, int v, int cost) {
nodes[ptr] = {{v, cost}, head[u]};
head[u] = ptr;
ptr++;
}
int main() {
int m;
fin >> n >> m;
for(int i = 0; i < n; i++) {
head[i] = NIL;
}
ptr = 0;
for(int i = 0; i < m; i++) {
int u, v, cost;
fin >> u >> v >> cost;
u--;
v--;
add_edge(u, v, cost);
}
dijkstra(0);
for(int i = 1; i < n; i++) {
fout << (min_cost[i] == INF ? 0 : min_cost[i]) << " ";
}
fout << "\n";
return 0;
}