给定两个整数N和K ,其中N表示游戏开始时出现的总牌数, K表示单回合可以移除的最大牌数。两名玩家A和B轮流移除最多K张牌,从玩家A开始一张一张。移除最后一张牌的玩家为获胜者。任务是检查A是否可以赢得比赛。如果发现是真的,请打印“ A”作为答案。否则,打印‘B’ 。
例子:
Input: N = 14, K = 10
Output: Yes
Explanation:
Turn 1: A removes 3 cards in his first turn.
Turn 2: B removes any number of cards from the range [1 – 10]
Finally, A can remove all remaining cards and wins the game, as the number of remaining cards after turn 2 will be ≤ 10
Input: N = 11, K=10
Output: No
方法:这里的想法是观察到,每当N%(K + 1)= 0的值时, A都将无法赢得比赛。否则, A总是赢球。
证明:
- If N ≤ K: The person who has the first turn will win the game, i.e. A.
- If N = K + 1: A can remove any number of cards in the range [1, K]. So, the total number of cards left after the first turn are also in the range [1, K]. Now B gets the turn and number of cards left are in the range [1, K]. So, B will win the game.
- If K + 2 ≤ N ≤ 2K + 1: A removes N – (K + 1) cards in his first turn. B can remove any number of cards in the range [1, K] in the next turn. Therefore, the total number of cards left now are in the range [1, K].Now, since the remaining cards left are in the range [1, K], so A can remove all the cards and win the game.
因此,该想法是检查N%(K + 1)是否等于0。如果发现是真的,则将B打印为获胜者。否则,将A打印为获胜者。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to check which
// player can win the game
void checkWinner(int N, int K)
{
if (N % (K + 1)) {
cout << "A";
}
else {
cout << "B";
}
}
// Driver code
int main()
{
int N = 50;
int K = 10;
checkWinner(N, K);
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to check which
// player can win the game
static void checkWinner(int N, int K)
{
if (N % (K + 1) > 0)
{
System.out.print("A");
}
else
{
System.out.print("B");
}
}
// Driver code
public static void main(String[] args)
{
int N = 50;
int K = 10;
checkWinner(N, K);
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program to implement
# the above approach
# Function to check which
# player can win the game
def checkWinner(N, K):
if(N % (K + 1)):
print("A")
else:
print("B")
# Driver Code
N = 50
K = 10
# Function call
checkWinner(N, K)
# This code is contributed by Shivam Singh
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to check which
// player can win the game
static void checkWinner(int N, int K)
{
if (N % (K + 1) > 0)
{
Console.Write("A");
}
else
{
Console.Write("B");
}
}
// Driver code
public static void Main(String[] args)
{
int N = 50;
int K = 10;
checkWinner(N, K);
}
}
// This code is contributed by Amit Katiyar
输出:
A
时间复杂度: O(1)
辅助空间: O(1)