Stack Machine

Time limit1sMemory limit128 MB

Summary
For each pair of intersections, find the shortest route whose sequence of board and leave events forms a balanced stack (empty at start and end).
Level

Hard8 of 10

Topics
Graph, Shortest path, Dynamic programming, Stack
Solved
No attempts yet

Problem

A stack machine is a special bus: it has a single door at the front, and it is so narrow that passengers cannot pass one another. The passenger who boards last must therefore be the first to get off, so the passengers behave like a stack (last in, first out).

The bus drives through a city whose intersections are connected by one-way roads. Driving along a road causes exactly one passenger to board or to get off. For each road the height of that passenger is fixed, and two passengers may have the same height.

A route is a sequence of roads the bus drives along. The bus must be empty at the start and at the end of the route, and whenever a passenger gets off it must be the passenger currently on top of the stack (whose height must equal the height fixed for that road). Plan routes between given intersections.

Input

The first line contains the number of test cases TT. Each test case begins with a line of three integers NN, MM, QQ: the number of intersections (1≤N≤1001 \le N \le 100), the number of roads (1≤M≤1000001 \le M \le 100000), and the number of queries (1≤Q≤1000001 \le Q \le 100000). Intersections are numbered 11 to NN. The next MM lines each contain three integers XX, YY, ZZ: a one-way road runs from intersection XX to intersection YY; if Z>0Z > 0 a passenger ZZ centimetres tall boards, and if Z<0Z < 0 a passenger −Z-Z centimetres tall gets off. Every passenger height is between 4040 and 220220 centimetres. The next QQ lines each contain two integers, the start and end intersections of a route.

Output

For each query, output on its own line the length (the number of roads) of the shortest non-empty route the bus can drive from the start intersection to the end intersection, beginning and ending empty. When such a route exists, its length is guaranteed to be at most 10910^9. If no such route exists, output the word impossible.

Examples2

  1. Example 1

    Input
    1
    2 2 4
    1 2 100
    2 1 -100
    1 1
    2 2
    1 2
    2 1
    
    Expected output
    2
    impossible
    impossible
    impossible
    
  2. Example 2

    Input
    1
    4 4 5
    1 2 10
    2 3 20
    3 4 -20
    4 1 -10
    1 1
    2 4
    1 4
    3 3
    4 4
    
    Expected output
    4
    2
    impossible
    impossible
    impossible