Where roads intersect, there are often traffic lights that tell pedestrians (people walking) when they should cross the street. A clever pedestrian may try to optimize her path through a city based on when those lights turn green.
The city in this problem is a grid,
The pedestrian can cross a street in 1 minute, but only if the traffic light is green for the entire crossing. The pedestrian can move between two streets, along one edge of a block, in 2 minutes. The pedestrian can only move along the edges of the block; she cannot move diagonally from one corner of a block to the opposite corner.

Traffic lights follow the following pattern: at intersection
For example, intersection 0 could have the following values:
The north-south direction turns green after 0 minutes. That lasts 3 minutes, during which time the pedestrian can cross in the north-south direction and not the east-west direction. Then the lights switch, and for the next 2 minutes the pedestrian can cross in the east-west direction and not the north-south direction. Then, 5 minutes after it started, the cycle starts again. This is exactly the same as the following configuration:
Input Specification
The first line in the input contains the number of test cases,
A single line containing N M
, where
Output Specification
For each test case, output a single line containing the text Case #x: t
, where
Limits
Time limit: 30 seconds per test set.
Memory limit: 1 GB.
Small Dataset
Large Dataset
Sample Input
2
1 1
3 2 10
1 2
1 5 3 1 5 2
Sample Output
Case #1: 4
Case #2: 7
Explanation for Sample
The first case is described above. The pedestrian crosses to the North (1 minute), waits 2 minutes and then crosses to the East (1 minute), for a total of 4 minutes.
The second case is depicted in the diagram below. The pedestrian crosses to the East (1 minute), waits 2 minutes and crosses to the North (1 minute). Then she walks east a block (2 minutes) and crosses to the East (1 minute) for a total of 7 minutes.

Comments