给定一个整数N ,两个玩家 A 和 B 的任务是通过交替轮换将X与范围[2, 9]中的任何数字相乘,使X的值(以1初始化)至少为N。假设两个玩家都发挥最佳。任务是找到玩家获得valuie≥N个第一。
例子:
Input: N = 12
Output: Player B
Explanation:
Initially, X = 1.
A multiplies X with 9. Therefore, X = 1 * 9 = 9.
In second turn, B multiplies X with 2. Therefore, X = 9*2 = 18
Therefore, B wins.
Input: N = 10
Output: Player B
方法:这个想法是使用组合博弈论的概念。找出位置,如果一个数字乘以X导致胜利,以及导致失败的位置。以下是步骤:
- 在组合博弈论中,让我们定义N 位置是下一个移动的玩家如果他玩得最佳而获胜的位置,而P 位置是一个位置,如果他的对手玩得最佳,下一个移动的玩家总是输。
- 可以达到N的最低位置是res = ceil(N/9) 。因此,从[res, res + 1, res + 2, ….., N – 1] 的所有位置都是N 个位置。
- 唯一被迫移动到[res, res + 1, …, (N – 1)] 的位置是那些乘以2 的位置,并且它们位于该区间内,该区间由Y = ceil(res/2 ) ,
- 因此, [Y, Y + 1, …, (res – 1)]都是P 位置。
- 重复以上步骤直到找到包含1的区间,如果1是N位,则A胜,否则B胜。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the winner
char Winner(int N)
{
bool player = true;
// Backtrack from N to 1
while(N > 1)
{
int den = (player) ? 9 : 2;
int X = N/den, Y = N%den;
N = (Y)? X + 1: X;
player = !player;
}
if (player)
return 'B';
else
return 'A';
}
// Driver Code
int main()
{
int N = 10;
cout << Winner(N);
return 0;
}
// This code is contributed by mohit kumar 29.
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to find the winner
static char Winner(int N)
{
boolean player = true;
// Backtrack from N to 1
while(N > 1)
{
int den = (player) ? 9 : 2;
int X = N / den;
int Y = N % den;
N = (Y > 0) ? X + 1: X;
player = !player;
}
if (player)
return 'B';
else
return 'A';
}
// Driver Code
public static void main(String[] args)
{
int N = 10;
System.out.print(Winner(N));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program for the above approach
# Function to find the winner
def Winner(N):
player = True
# Backtrack from N to 1
while N > 1:
X, Y = divmod(N, (9 if player else 2))
N = X + 1 if Y else X
player = not player
if player:
return 'B'
else:
return 'A'
# Driver Code
N = 10
print(Winner(N))
C#
// C# program for the above approach
using System;
class GFG
{
// Function to find the winner
static char Winner(int N)
{
bool player = true;
// Backtrack from N to 1
while (N > 1)
{
int den = (player) ? 9 : 2;
int X = N / den;
int Y = N % den;
N = (Y > 0) ? X + 1 : X;
player = !player;
}
if (player)
return 'B';
else
return 'A';
}
// Driver Code
static public void Main()
{
int N = 10;
Console.WriteLine(Winner(N));
}
}
// This code is contributed by Dharanendra L V
Javascript
输出:
B
时间复杂度: O(log N)
辅助空间: O(1)