Pagini recente » Cod sursa (job #2791883) | Cod sursa (job #1308210) | Cod sursa (job #2198668) | Cod sursa (job #2712816) | Cod sursa (job #1486333)
#include <bits/stdc++.h>
using namespace std;
struct graph{
graph *next;
int to;
int length;
};
graph *e[50005];
bool v[50005];
int d[50005];
deque<pair<int, int>> q;
int main()
{
FILE *f = fopen("dijkstra.in", "r");
FILE *g = fopen("dijkstra.out", "w");
int n, m;
fscanf(f, "%d %d", &n, &m);
for(int i = 1; i <= m; i ++) {
int a, b, c;
fscanf(f, "%d %d %d", &a, &b, &c);
graph *one = new graph;
one->to = b;
one->length = c;
one->next = e[a];
e[a] = one;
}
for(int i = 2; i <= n; i ++)
d[i] = 50000000;
v[1] = true;
q.push_back(make_pair(1, 0));
while(!q.empty()) {
int i = q.front().first;
d[i] = q.front().second;
q.pop_front();
graph *cur = e[i];
while(cur != NULL) {
int pos = 0;
int mn = 50000001;
while(cur != NULL) {
if(cur->length < mn) {
mn = cur->length;
pos = cur->to;
}
cur = cur->next;
}
cur = e[i];
graph *past = NULL;
graph *ret = cur;
while(cur != NULL) {
if(cur->length == mn && cur->to == pos) {
graph *del = cur;
cur = cur->next;
if(past != NULL)
past->next = cur;
else
ret = cur;
delete(del);
}
if(cur != NULL) {
past = cur;
cur = cur->next;
}
}
e[i] = ret;
if(!v[pos] || d[pos] > d[i] + mn) {
d[pos] = d[i] + mn;
v[pos] = true;
q.push_back(make_pair(pos, d[i] + mn));
}
cur = e[i];
}
}
for(int i = 2; i <= n; i ++) {
fprintf(g, "%d ", d[i]);
}
fprintf(g, "\n");
return 0;
}