Floyd : City of Blinding Lights
Difficulty: Hard

Given a directed weighted graph where weight indicates distance, for each query, determine the length of the shortest path between nodes.  There may be many queries, so efficiency counts.  

For example, your graph consists of $5$ nodes as in the following:



![image](https://s3.amazonaws.com/hr-assets/0/1525461069-142e0d306a-blindingLightsExample.png)  

A few queries are from node $4$ to node $3$, node $2$ to node $5$, and node $5$ to node $3$.  
<br>

1. There are two paths from $4$ to $3$:
	+	$4 \Rightarrow 1 \Rightarrow 2 \Rightarrow 3$ at a distance of $4 + 5 + 1 = 10$  
    +	$4 \Rightarrow 1 \Rightarrow 5 \Rightarrow 3$ at a distance of $4 + 3 + 2 = 9$  
  	In this case we choose path $2$.  
      
2. There is no path from $2$ to $5$, so we return $-1$.  
  
3. There is one path from $5$ to $3$:  
	+	$5 \Rightarrow 3$ at a distance of $2$.  
    

Input Format:
The first line has two integers $n$ and $m$, the number of nodes and the number of edges in the graph.  
Each of the next $m$ lines contains three space-separated integers $u$ $v$ and $w$, the two nodes between which the _directed_ edge $u \Rightarrow v$ exists, and $w$, the length of the edge.  
The next line contains a single integer $q$, the number of queries.  
Each of the next $q$ lines contains two space-separated integers $a$ and $b$, denoting the start and end nodes for traversal.  

Output Format:
Print $q$ lines, each containing a single integer specifying the shortest distance for the query.  

If the destination node is not reachable, return $-1$.  

Sample Input:
<pre>
STDIN	Function
-----	--------
4 5		n = 4, m = 5
1 2 5	u = 1, v = 2, w = 5
1 4 24	u = 1, v =4, w = 24 ...
2 4 6
3 4 4
3 2 7
3		q = 3
1 2		query 0: from 1 to 2
3 1		query 1: from 3 to 1
1 4		query 2: from 1 to 4
</pre>

Sample Output:
    5
    -1
    11

Python 3 starter code:


Reference solution (C++):
###C++  
```cpp  
'#'define INF 9999999

using namespace std;

int main() 

{
    
int n,m,i,x,y,r,a,b,j,k,q;
cin>>n>>m;
int adj[n][n];
for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        adj[i][j]=INF;
    }
}
for(i=0;i<n;i++)
adj[i][i]=0;
int floyd[n][n];
for(i=0;i<m;i++)
{
    cin>>x>>y>>r;
    adj[x-1][y-1]=r;
}
for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        floyd[i][j]=adj[i][j];
    }
}
for(k=0;k<n;k++)
{
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            floyd[i][j]=min(floyd[i][j],floyd[i][k]+floyd[k][j]);
        }
    }
}
cin>>q;
while(q--)
{
    cin>>a>>b;
    int ans=floyd[a-1][b-1];
    if(ans!=INF)
    cout<<ans<<endl;
    else
    cout<<"-1\n";
}
return 0;
}
```