📌  相关文章
📜  找到玩家能够替换其除数可以替换的最后一个元素

📅  最后修改于: 2021-04-17 16:02:03             🧑  作者: Mango

给定一个数组arr [] ,该数组由N个整数组成,并且两个玩家AB通过执行以下操作一起玩游戏:

  • arr []中选择一个整数,然后用其除数之一替换该数字。
  • 先前选择的整数不能再次选择。
  • 由于1除自身以外没有其他除数,因此玩家无法将1除以任何其他数字。因此,当数组仅包含1 s时,无法采取任何行动的玩家将输掉比赛。
  • 双方都将发挥最佳状态,而A则是比赛的第一步。

任务是找到游戏的获胜者。

例子:

方法:可以通过简单的观察来解决问题:

  • 由于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


输出:
B

时间复杂度: O(N),其中N是数组的大小。
辅助空间:O(1)