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 79 80 81 82
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define INF 1000000000
#define MAX 100
int G[MAX][MAX], c[MAX][MAX], U[MAX],
p[MAX],d[MAX],n,m;
void dijkstra(int r)
{
int v , w, min ,i ,j;
for(i =1; i<=n; i++)
{
U[i]=0; p[i]=r; d[i]=INF;
}
d[r]=p[r]=0;
for(i=1;i<=n;i++)
{
v = 0; min = INF;
for(j=1;j<=n;j++)
{
if(U[j]==0 && d[j]<min)
{
v= j; min=d[j];
}
U[v]=1;
for(j=1;j<=G[v][0];j++)
{
w=G[v][j];
if(U[w] == 0 && d[v]+c[v][w]<d[w])
{
d[w]=d[v]+c[v][w];
p[w]=v;
}
}
}
}
}
int main ()
{
int u,v,w,i,j,z,x,y;
//n = number of villages and m = number of paths between villages : 5 and 8 from the example input
scanf("%d %d", &n, &m);
//z,x,y the different times to go through villages : 25 30 30 from the example input
scanf("%d %d %d", &z, &x, &y);
for(i=1;i<=n;i++)
{
G[i][0]=0;
for(j=1;j<=n;j++)
{
c[i][j]=INF;
}
if(i==j)
{
c[i][j]=0;
}
}
for(i =1; i<=m;i++)
{
/*u is the village node, v is the target village node, w is the time to travel from one node to another
(e.g the weight of the path in graph term) : 1 3 100, 1 2 80 , 1 4 20 - From example input*/
scanf("%d %d %d", &u, &v, &w);
G[u][++G[u][0]]=v;
G[v][++G[v][0]] = u;
c[u][v]=c[v][u]=w;
}
//runs dijkstra from the first node. E.g finds the shortest path from village node 1.
dijkstra(1);
//prints the shortest path
for(i=1;i<=n;i++)
{
printf("%d %d\n",i,p[i]);
}
return 0;
}
|