Pagini recente » Cod sursa (job #2212242) | Cod sursa (job #885115) | Cod sursa (job #2631220) | Cod sursa (job #3130533) | Cod sursa (job #3296312)
#include <bits/stdc++.h>
const int MAXN = 50'000;
const int BUFSIZE = (2 * 131'072);
const int INF = 2'000'000'000;
int n, m;
struct Edge{
int u, cost;
bool operator <(const Edge &a) const {
return cost > a.cost;
}
};
std::vector<Edge> adj[MAXN + 1];
class InParser {
private:
FILE * fin;
char * buff;
int sp;
char read_ch() {
++sp;
if(sp == BUFSIZE) {
sp = 0;
fread(buff, 1, BUFSIZE, fin);
}
return buff[sp];
}
public:
InParser(const char * nume) {
fin = fopen(nume, "r");
buff = new char[BUFSIZE]();
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");
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( Edge nxt : adj[e.u] ) {
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 = 0; i < m; i++ ) {
int u, v, w;
fin >> u >> v >> w;
adj[u].push_back({v, w});
}
dijkstra(1);
return 0;
}