通过在范围 [1, K] 中选择一个总和为 N 的数字来找到将获胜的玩家
给定两个整数K和N ,并且还假设Alice和Bob正在玩游戏。在单步棋中,玩家可以在[1, K]范围内选择一个数字,其数字使总和等于N的玩家获胜。如果Alice赢得游戏,则打印Alice ,否则打印Bob ,如果Alice和Bob都交替且最优地玩游戏并且Alice开始游戏。
例子:
Input: K = 7, N = 8
Output: Bob
Explanation: There is no way for Alice to win the game. When Alice picks any number from 1 to 7 (inclusive both), the opponent wins the game in the next turn by making the total 8 . Suppose you choose number 5, the opponent chooses 3 and wins the game, making the total 5+3=8 .
Input: K = 7, N = 50
Output: Alice
方法:这个问题可以用博弈论的概念来解决。观察获胜状态。这里要抓住的诀窍是,无论Bob选择什么, Alice总是可以重复(K+1) 的循环。假设在某个时刻,如果Bob选择a , Alice可以选择[(K+1)-a ]将选择保持在1 到 K 的范围内,从而形成一个(K+1) 的循环。现在,由于Alice有第一次机会, Alice应该选择Remainder left on Dividing N by (K+1) at the Starting 以便之后,她可以继续重复(K+1) 的循环并达到总数为N 。
现在,观察结果是,如果N%(K+1) 为 0 ,这是唯一不可能为 Alice 赢得比赛的情况。
请按照以下步骤解决问题。
- 检查N%(K+1) 是否为 0,打印Bob 。
- 在任何其他情况下,打印Alice 。
下面是上述方法的实现。
C++14
// C++ program for above approach
#include
using namespace std;
// Function to predict the winner
void predictTheWinner(int K, int N)
{
if (N % (K + 1) == 0)
cout << "Bob";
else
cout << "Alice";
}
// Driver Code
int main()
{
// Given Input
int K = 7, N = 50;
// Function call
predictTheWinner(K, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG {
// Function to predict the winner
static void predictTheWinner(int K, int N)
{
if (N % (K + 1) == 0)
System.out.println( "Bob");
else
System.out.println("Alice");
}
// Driver Code
public static void main (String[] args) {
// Given Input
int K = 7, N = 50;
// Function call
predictTheWinner(K, N);
}
}
// This code is contributed by Potta Lokesh
Python3
# Python 3 program for above approach
# Function to predict the winner
def predictTheWinner(K, N):
if (N % (K + 1) == 0):
print("Bob")
else:
print("Alice")
# Driver Code
if __name__ == '__main__':
# Given Input
K = 7
N = 50
# Function call
predictTheWinner(K, N)
# This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach
using System;
public class GFG {
// Function to predict the winner
static void predictTheWinner(int K, int N)
{
if (N % (K + 1) == 0)
Console.WriteLine( "Bob");
else
Console.WriteLine("Alice");
}
// Driver Code
public static void Main (string[] args) {
// Given Input
int K = 7, N = 50;
// Function call
predictTheWinner(K, N);
}
}
// This code is contributed by AnkThon
Javascript
Alice
时间复杂度: O(1)
辅助空间: O(1)