Pagini recente » Cod sursa (job #676661) | Cod sursa (job #1106858) | Cod sursa (job #2317558) | Cod sursa (job #1149393) | Cod sursa (job #1486365)
#include <bits/stdc++.h>
using namespace std;
struct graph{
graph *next;
int to;
int length;
};
graph *e[50005];
graph *E[50005];
bool v[50005];
long long 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 = 1; i <= n; i ++) {
graph *one = new graph;
one = e[i];
E[i] = one;
}
for(int i = 2; i <= n; i ++)
d[i] = 50000000;
q.push_back(make_pair(1, 0));
while(!q.empty()) {
int i = q.front().first;
if(d[i] > q.front().second) {
d[i] = q.front().second;
if(e[i] == NULL)
e[i] = E[i];
}
v[i] = true;
q.pop_front();
graph *cur = e[i];
while(cur != NULL) {
int pos = 0;
long long 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) {
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;
}