假设我们有两个数字 c 和 d。Amal 有两个数字 a 和 b,最初都是零。Amal 想对它们进行一些操作。在执行每个操作之前,选择一些正整数 k,然后将其用于执行以下操作之一 -
将数字 k 添加到 a 和 b,或
将数字 k 加到 a 并从 b 中减去 k,或
将数字 k 加到 b 并从 a 中减去 k。
我们必须找到使 a 和 b 分别等于 c 和 d 所需的最小操作数。如果不可能,则返回 -1。
所以,如果输入像 c = 3; d = 5,则输出为 2,因为对于 k = 1,我们得到数字 (1, 1),对于 k = 8,该对可以是 (-7, 9),对于 k = 7,它可以是 (0, 2) 并且对于 k = 3,它可以是 (3, 5)
脚步
为了解决这个问题,我们将遵循以下步骤 -
if (c ^ d) is odd, then: return -1 otherwise when c is same as 0 and d is same as 0, then: return 0 otherwise when c is same as d, then: return 1 Otherwise return 2
示例
让我们看看以下实现以更好地理解 -
#include <bits/stdc++.h> using namespace std; int solve(int c, int d){ if ((c ^ d) & 1) return -1; else if (c == 0 && d == 0) return 0; else if (c == d) return 1; else return 2; } int main(){ int c = 3; int d = 5; cout << solve(c, d) << endl; }
输入
3, 5输出结果
2