SSSP (Shortest Path Queries)

No attempts yetTime limit1sMemory limit128 MB

Problem

Given a directed weighted graph GG and two vertices ss and tt, let p(s,t)p(s, t) be the sum of the edge weights along a shortest path from ss to tt. If tt is unreachable from ss, define p(s,t)p(s, t) to be 1,000,000,000.

The input consists of the graph GG and QQ queries (s1,t1),(s2,t2),,(sQ,tQ)(s_1, t_1), (s_2, t_2), \dots, (s_Q, t_Q). For each query kk, output p(sk,tk)p(s_k, t_k).

The graph may contain edges with negative weights, but it never contains a cycle whose total weight is negative.

Input

The input is made of two blocks. The first block describes the adjacency list of the graph GG; the second block describes the queries.

The first line of the first block contains the number of vertices VV. Vertices are numbered from 00 to V1V-1. Each of the next VV lines describes one vertex, starting from vertex 00 in order. On each line, the first number nin_i is the number of edges leaving vertex ii, followed by nin_i pairs (j,w)(j, w). Each pair denotes an edge from vertex ii to vertex jj with weight ww.

The first line of the second block contains the number of queries QQ, followed by QQ lines, each containing sks_k and tkt_k.

Two consecutive integers on the same line are separated by a single space. The input satisfies the following conditions.

  1. 0<V3000 < V \le 300
  2. nin_i is a non-negative integer.
  3. 0j<V0 \le j < V
  4. w<106|w| < 10^6
  5. 0i=0V1ni50000 \le \sum_{i=0}^{V-1} n_i \le 5000
  6. 0<Q100 < Q \le 10
  7. 0sk<V0 \le s_k < V, 0tk<V0 \le t_k < V
  8. The graph GG contains no cycle whose total weight is negative.

Output

Print QQ lines. The kk-th line contains the value of p(sk,tk)p(s_k, t_k).

On the last line, print the final value of the counter variable accumulated while running the algorithm defined in the "Hint" section below, using the following format.

The value of counter is: <counter>

Hint

Each query (sk,tk)(s_k, t_k) is processed with the queue-based Bellman-Ford (SPFA) algorithm below. The counter variable accumulates across all queries and is never reset between queries.

counter ← 0
for each query (s, t) in input order:
    dist[v] ← ∞ for every vertex v,  and dist[s] ← 0
    inQueue[v] ← false for every vertex v
    empty the FIFO queue, then push s
    inQueue[s] ← true;   counter ← counter + 1
    while the queue is not empty:
        u ← pop from the queue;   inQueue[u] ← false
        for each edge (u → v, weight w) in u's adjacency list, in input order:
            if dist[u] + w < dist[v]:
                dist[v] ← dist[u] + w
                if inQueue[v] = false:
                    push v;   inQueue[v] ← true;   counter ← counter + 1
    p(s, t) = dist[t] if dist[t] < ∞ else 1,000,000,000

In other words, counter is the total number of times any vertex is pushed onto the queue over the whole run, counting the initial push of the source ss at the start of each query as one.