给定21个火柴杆和2个用户,A和B(分别为计算机和用户)。用户一次最多只能挑四根火柴。被迫挑起最后一根火柴的人输了。
给定一个数组arr [] ,它包含计算机的移动。任务是打印用户的动作,以便用户赢得游戏。
例子:
Input : N = 4, arr=[ 3, 4, 2, 2]
Output : 2, 1, 3, 3
When the computer chooses 3 sticks, the user chooses 2 sticks
When the computer chooses 4 sticks, the user chooses 1 stick
When the computer chooses 2 sticks, the user chooses 3 sticks
When the computer chooses 2 sticks, the user chooses 3 sticks
Now only 1 stick is left and the computer is forced to pick that stick
Hence the user wins the game.
Input : N = 4 arr=[ 1, 1, 4, 3]
Output : 4, 4, 1, 2
方法:
- 想法是考虑使用20个火柴,因为选择最后一个火柴的用户将输掉比赛。
- 将20分成四个部分,每个部分的大小为5。因此,如果计算机选择了x个火柴棍,则用户应选择(5-x)个火柴棍,并以相同的方式进行操作。
- 这样,将使用20个火柴,计算机将拾取最后一个火柴。
下面是上述方法的实现
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the optimal strategy
void TwentyoneMatchstick(int arr[], int N)
{
// Removing matchsticks in blocks of five
for (int i = 0; i < N; i += 1) {
cout << 5 - arr[i] << " ";
}
cout << endl;
}
// Driver code
int main()
{
int arr[] = { 3, 4, 2, 2 };
int N = sizeof(arr) / sizeof(arr[0]);
TwentyoneMatchstick(arr, N);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the optimal strategy
static void TwentyoneMatchstick(int arr[], int N)
{
// Removing matchsticks in blocks of five
for (int i = 0; i < N; i += 1)
{
System.out.print(5 - arr[i] + " ");
}
System.out.println();
}
// Driver code
public static void main(String[] args)
{
int arr[] = {3, 4, 2, 2};
int N = arr.length;
TwentyoneMatchstick(arr, N);
}
}
// This code is contributed by Princi Singh
Python3
# Python3 implementation of the approach
# Function to return the optimal strategy
def TwentyoneMatchstick(arr, N):
# Removing matchsticks in blocks of five
for i in range(N):
print(5 - arr[i], end = " ")
# Driver code
arr = [3, 4, 2, 2 ]
N = len(arr)
TwentyoneMatchstick(arr, N)
# This code is contributed
# by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the optimal strategy
static void TwentyoneMatchstick(int []arr, int N)
{
// Removing matchsticks in blocks of five
for (int i = 0; i < N; i += 1)
{
Console.Write(5 - arr[i] + " ");
}
Console.Write("\n");
}
// Driver code
public static void Main(String[] args)
{
int []arr = {3, 4, 2, 2};
int N = arr.Length;
TwentyoneMatchstick(arr, N);
}
}
// This code is contributed by Princi Singh
输出:
2 1 3 3
时间复杂度: O(N)