Here is the solution:
INF = 10^18
dist = 2D array of size (n+1) x (n+1), all INF
for i from 1 to n:
dist[i][i] = 0
for each edge (a, b, w):
dist[a][b] = min(dist[a][b], w)
dist[b][a] = min(dist[b][a], w)
for k from 1 to n:
for i from 1 to n:
for j from 1 to n:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
for each query (a, b):
if dist[a][b] >= INF:
print -1
else:
print dist[a][b]
Use a large constant like for infinity to avoid overflow when adding.
This runs in time and uses space.