Pagini recente » Cod sursa (job #1237081) | Cod sursa (job #3270521) | Cod sursa (job #1490611) | Cod sursa (job #1651205) | Cod sursa (job #1988800)
#include <cstdio>
#define NMAX 200000
#define INF 1e9
using namespace std;
FILE *f = freopen("dijkstra.in", "r", stdin);
FILE *g = freopen("dijkstra.out", "w", stdout);
struct node{
int vertex;
int cost;
node *next;
};
node *a[NMAX];
int n, m, first, last;
int myQueue[NMAX], dist[NMAX];
bool inQueue[NMAX];
void insertBeginning(node *& head, int cost, int vertex) {
node *tmp = new node;
tmp -> vertex = vertex;
tmp -> cost = cost;
tmp -> next = head;
head = tmp;
}
void readData() {
scanf("%d%d", &n, &m);
for(int i = 1; i<=m; i++) {
int v1, v2, cost;
scanf("%d%d%d", &v1, &v2, &cost);
insertBeginning(a[v1], cost, v2);
}
}
void printData(node *& head) {
node *tmp = head;
while(tmp != NULL) {
printf("%d ", tmp -> vertex);
tmp = tmp -> next;
}
}
void dijkstra(int start){
inQueue[start] = true;
first = last = 1;
myQueue[first] = start;
for(int i = 0; i<=n; i++)
dist[i] = INF;
dist[start] = 0;
while(first <= last) {
int currNode = myQueue[first];
first ++;
node *tmpHead = a[currNode];
inQueue[currNode] = false;
while(tmpHead != NULL) {
if(dist[currNode] + tmpHead -> cost < dist[tmpHead -> vertex]) {
dist[tmpHead -> vertex] = dist[currNode] + tmpHead -> cost;
if(!inQueue[tmpHead -> vertex]) {
last ++;
myQueue[last] = tmpHead -> vertex;
inQueue[tmpHead -> vertex] = true;
}
}
tmpHead = tmpHead -> next;
}
}
}
int main() {
readData();
dijkstra(1);
dijkstra(1);
for(int i = 2; i<=n; i++)
if(dist[i] != INF) printf("%d ", dist[i]);
else printf("0 ");
}