📌  相关文章
📜  通过乘以给定范围内的任何值来找到至少达到N的玩家

📅  最后修改于: 2021-04-17 17:19:55             🧑  作者: Mango

给定一个整数N ,两个玩家A和B的任务是通过交替将X与范围[2,9]中的任何数字相乘,使X的值(1初始化)至少为N。假设两个玩家都发挥最佳状态。任务是找到玩家获得valuie≥N个第一。

例子:

方法:这个想法是使用组合博弈论的概念。如果数字乘以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


输出:
B

时间复杂度: O(log N)
辅助空间: O(1)