鉴于两个整数X和Y分别代表分配给玩家A和B的糖果,其中两个玩家在捐赠我的沉迷游戏的数量糖果对手在每一个第i个举动。从玩家A开始,游戏交替进行,直到玩家无法捐赠所需数量的糖果并输掉游戏为止,任务是找到游戏的获胜者。
例子:
Input: X = 2, Y = 3
Output: A
Explanation: The game turns out in the following manner:
Step |
X |
Y |
0 |
2 |
3 |
1 |
1 |
4 |
2 |
3 |
2 |
3 |
0 |
5 |
4 |
4 |
1 |
Since A fails to donate 5 candies in the 5th step, B wins the game.
Input: X = 2, Y = 1
Output: B
Explanation: The game turns out in the following manner:
Step | X | Y |
0 | 2 | 1 |
1 | 1 | 2 |
2 | 3 | 0 |
3 | 0 | 3 |
Since B fails to give 4 candies in the 4th step, A wins the game.
方法:想法是基于以下观察结果解决问题:
Step |
Number of candies |
Number of candies |
0 |
X |
Y |
1 |
X – 1 |
Y + 1 |
2 |
X – 1 + 2 = X + 1 |
Y + 1 – 2 = Y – 1 |
3 |
X – 2 |
Y + 2 |
4 |
X + 2 |
Y – 2 |
- The player whose candies reduce to 0 first, will not be having enough candies to give in the next move.
- Count of candies of player A decreases by 1 in odd moves.
- Count of candies of player B decreases by 1 in even moves.
请按照以下步骤解决问题:
- 初始化两个变量,分别是机会A和机会B,代表玩家拥有的糖果数量减少到0的移动次数。
- 由于玩家A的糖果数在奇数步中减少1,因此机会A = 2 *(X – 1)+ 1
- 由于玩家B的糖果数在均匀移动中减少1,因此偶然机会B = 2 * Y
- 如果机会A <机会B ,则B将是获胜玩家。
- 否则, A将是获胜者。
- 打印获胜的玩家。
下面是上述方法的实现:
C++
// C++ Program for the
// above approach
#include
using namespace std;
// Function to find the winning
// player in a game of donating i
// candies to opponent in i-th move
int stepscount(int a, int b)
{
// Steps in which number of
// candies of player A finishes
int chanceA = 2 * a - 1;
// Steps in which number of
// candies of player B finishes
int chanceB = 2 * b;
// If A's candies finishes first
if (chanceA < chanceB) {
cout << "B";
}
// Otherwise
else if (chanceB < chanceA) {
cout << "B";
}
return 0;
}
// Driver Code
int main()
{
// Input
// Candies possessed
// by player A
int A = 2;
// Candies possessed
// by player B
int B = 3;
stepscount(A, B);
return 0;
}
输出:
B
时间复杂度: O(1)
辅助空间: O(1)