forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.c
executable file
·78 lines (72 loc) · 1.12 KB
/
dijkstra.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<stdio.h>
#include<stdlib.h>
#define N (int)1e5
#define M (int)1e6
const int INF = (int)1e9;
int max(int a, int b)
{
if(a<b) return b;
return a;
}
int* G[N];
int* W[N];
int deg[N],U[M],V[M],weight[M],cnt[N];
int Q[N],dis[N];
// Heap functions
struct node
{
int v,d;
}node;
int empty();
node top();
void pop();
void insert(int v, int d);
void bfs(int src)
{
int i;
for(i=1; i<=n; i++) dis[i] = INF;
dis[src] = 0;
insert(src,0);
while(!empty())
{
node x = top(); pop();
int u = x.v; int d = x.d;
if(d > dis[u]) continue;
for(i=0; i<cnt[u]; i++)
{
int v = G[u][i];
if(dis[u] + W[u][i] < dis[v])
{
dis[v] = dis[u] + W[u][i];
insert(v,dis[v]);
}
}
}
}
int main()
{
int n,m,i;
scanf("%d %d",&n,&m);
for(i=0; i<m; i++)
{
scanf("%d %d %d",&U[i],&V[i],&weight[i]);
deg[U[i]]++;
deg[V[i]]++;
}
for(i=1; i<=n; i++)
{
dis[i] = INF;
G[i] = (int*)malloc(deg[i]*sizeof(int));
}
for(i=0; i<m; i++)
{
int u = U[i], v = V[i];
G[u][cnt[u]] = v;
G[v][cnt[v]] = u;
W[u][cnt[u]++] = weight[i];
W[v][cnt[v]++] = weight[i];
}
bfs(1);
for(i=1; i<=n; i++)
printf("%d %d\n",i,dis[i]);
}