A. Direction Change

You are given a grid with n rows and m columns. Rows and columns are numbered from 1 to n, and from 1 to m. The intersection of the a-th row and b-th column is denoted by (a,b).

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

You can move in four directions from (a,b): up to (a−1,b), down to (a+1,b), left to (a,b−1) or right to (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)?

Input
The input consists of multiple test cases. The first line contains a single integer t (1≤t≤103) — the number of the test cases. The description of the test cases follows.

The first line of each test case contains two integers n and m (1≤n,m≤109) — the size of the grid.

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

Example
input

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

output

0
1
-1
6
10
17

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

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

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

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

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n, m;
int main() {
	int t;
	cin >> t;
	while (t--) {
		ll ans = 0;
		cin >> n >> m;
		if (n == 1 || m == 1) {
			if (n == 1 && m == 1) ans = 0;
			else if (m == 2 || n == 2) ans = 1;
			else ans = -1;
			cout << ans << endl;
			continue;
		}
		int t1 = min(n, m);
		ans = 2 * t1 - 2;
		int t2 = max(n, m);
		t2 = t2 - t1;
		if (t2 > 0) {
			if (t2 % 2 == 0) ans += t2 / 2 * 4;
			else ans += t2 / 2 * 4 + 1;
		}
		
		cout << ans << endl;;
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值