给定一个由N 个整数组成的数组arr[]和两个玩家A和B通过执行以下操作一起玩游戏:
- 从arr[] 中选择一个整数并将该数字替换为其一个除数。
- 不能再次选择先前选择的整数。
- 由于 1 没有除自身之外的任何除数,因此玩家不能用任何其他数字替换 1。因此,当数组仅由1 s 组成时,无法进行任何移动的玩家将输掉游戏。
- 两个玩家都会以最佳方式进行游戏, A进行游戏的第一步。
任务是找到游戏的赢家。
例子:
Input: arr[] = {24, 45, 45, 24}
Output: B
Explanation:
Player A replaces 24 in the first index with 1. Since, 1 is a divisor of 24. arr[] = {1, 45, 45, 24}
Player B replaces 24 in the last index with 1. Since, 1 is a divisor of 24. arr[] = {1, 45, 45, 1}
Player A replaces 45 in the second index with 1. Since, 1 is a divisor of 45. arr[] = {1, 1, 45, 24}
Player B replaces 45 in the third index with 1. Since, 1 is a divisor of 45. arr[] = {1, 1, 1, 1}
Player A cannot make a move now, since all elements are 1. Therefore, player B wins the game.
Input: arr[] = {18, 6}
Output: B
方法:这个问题可以基于一个简单的观察来解决:
- 由于 1 是所有整数的除数,因此,在每个操作中用 1 替换每个数组元素。
- 因此,如果数组由偶数个元素组成,则玩家 B 获胜。
- 否则,玩家 A 获胜。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the winner
// of the game played based on
// given conditions
void winner(int arr[], int N)
{
// A wins if size of array is odd
if (N % 2 == 1) {
cout << "A";
}
// Otherwise, B wins
else {
cout << "B";
}
}
// Driver Code
int main()
{
// Input array
int arr[] = { 24, 45, 45, 24 };
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
winner(arr, N);
}
Java
// Java program for the above approach
class GFG{
// Function to find the winner
// of the game played based on
// given conditions
static void winner(int arr[], int N)
{
// A wins if size of array is odd
if (N % 2 == 1)
{
System.out.print("A");
}
// Otherwise, B wins
else
{
System.out.print("B");
}
}
// Driver Code
public static void main(String[] args)
{
// Input array
int arr[] = { 24, 45, 45, 24 };
// Size of the array
int N = arr.length;
winner(arr, N);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program for the above approach
# Function to find the winner
# of the game played based on
# given conditions
def winner(arr, N):
# A wins if size of array is odd
if (N % 2 == 1):
print ("A")
# Otherwise, B wins
else:
print ("B")
# Driver Code
if __name__ == '__main__':
# Input array
arr = [24, 45, 45, 24]
# Size of the array
N = len(arr)
winner(arr, N)
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
public class GFG
{
// Function to find the winner
// of the game played based on
// given conditions
static void winner(int []arr, int N)
{
// A wins if size of array is odd
if (N % 2 == 1)
{
Console.Write("A");
}
// Otherwise, B wins
else
{
Console.Write("B");
}
}
// Driver Code
public static void Main(String[] args)
{
// Input array
int []arr = { 24, 45, 45, 24 };
// Size of the array
int N = arr.Length;
winner(arr, N);
}
}
// This code contributed by shikhasingrajput
Javascript
B
时间复杂度: O(N),其中 N 是数组的大小。
辅助空间:O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。