CF1668A.Direction Change

入门

通过率:0%

时间限制:1.00s

内存限制:256MB

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

You are given a grid with nn rows and mm columns. Rows and columns are numbered from 11 to nn, and from 11 to mm. The intersection of the aa-th row and bb-th column is denoted by (a,b)(a, b).

Initially, you are standing in the top left corner (1,1)(1, 1). Your goal is to reach the bottom right corner (n,m)(n, m).

You can move in four directions from (a,b)(a, b): up to (a−1,b)(a-1, b), down to (a+1,b)(a+1, b), left to (a,b−1)(a, b-1) or right to (a,b+1)(a, b+1).

You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach (n,m)(n, m)?

你被给定一个 nn 行 mm 列的网格。行和列均从 11 编号至 nn 和从 11 编号至 mm。第 aa 行与第 bb 列的交点记为 (a,b)(a, b)。

初始时,你位于左上角 (1,1)(1, 1)。你的目标是到达右下角 (n,m)(n, m)。

你可以从 (a,b)(a, b) 向四个方向移动:向上至 (a−1,b)(a-1, b)、向下至 (a+1,b)(a+1, b)、向左至 (a,b−1)(a, b-1) 或向右至 (a,b+1)(a, b+1)。

你不能在连续两步中沿相同方向移动,且不能移出网格边界。问:到达 (n,m)(n, m) 所需的最少移动步数是多少?

输入格式

The input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1031 \le t \le 10^3) — the number of the test cases. The description of the test cases follows.

The first line of each test case contains two integers nn and mm (1≤n,m≤1091 \le n, m \le 10^9) — the size of the grid.

输入包含多个测试用例。第一行包含一个整数 tt(1≤t≤1031 \le t \le 10^3),表示测试用例的数量。随后是各测试用例的描述。

每个测试用例的第一行包含两个整数 nn 和 mm(1≤n,m≤1091 \le n, m \le 10^9),表示网格的大小。

输出格式

For each test case, print a single integer: −1-1 if it is impossible to reach (n,m)(n, m) under the given conditions, otherwise the minimum number of moves.

对于每个测试用例,输出一个整数:若在给定条件下无法到达 (n,m)(n, m),则输出 −1-1;否则输出最少移动步数。

输入输出样例

  • 输入#1

    6
    1 1
    2 1
    1 3
    4 2
    4 6
    10 5

    输出#1

    0
    1
    -1
    6
    10
    17

说明/提示

Test case 11: n=1n=1, m=1m=1, and initially you are standing in (1,1)(1, 1) so 00 move is required to reach (n,m)=(1,1)(n, m) = (1, 1).

Test case 22: you should go down to reach (2,1)(2, 1).

Test case 33: it is impossible to reach (1,3)(1, 3) without moving right two consecutive times, or without leaving the grid.

Test case 44: an optimal moving sequence could be: (1,1)→(1,2)→(2,2)→(2,1)→(3,1)→(3,2)→(4,2)(1, 1) \to (1, 2) \to (2, 2) \to (2, 1) \to (3, 1) \to (3, 2) \to (4, 2). It can be proved that this is the optimal solution. So the answer is 66.

测试用例 11:n=1n=1,m=1m=1,初始时你位于 (1,1)(1, 1),因此到达 (n,m)=(1,1)(n, m) = (1, 1) 所需移动次数为 00。

测试用例 22:你需要向下移动以到达 (2,1)(2, 1)。

测试用例 33:若不连续向右移动两次,或不移出网格边界,则无法到达 (1,3)(1, 3)。

测试用例 44:一种最优移动序列为:(1,1)→(1,2)→(2,2)→(2,1)→(3,1)→(3,2)→(4,2)(1, 1) \to (1, 2) \to (2, 2) \to (2, 1) \to (3, 1) \to (3, 2) \to (4, 2)。可以证明该序列是最优解。因此答案为 66。

输入解题思路,AI测评打分。不知道怎么写?

首页