logo

조합 게임 이론 | 세트 4 (Sprague -Grundy Theorem)

전제 조건 : Grundy 번호/번호 및 Mex
우리는 이미 게임을하지 않고 NIM 게임에서 이길 수있는 사람을 찾을 수있는 2 세트 (https://www.geeksforgeeks.org/combinatorial-game-them-theor-2-game-mam/)에서 이미 보았습니다.
우리가 클래식 NIM 게임을 조금 변경한다고 가정 해 봅시다. 이번에는 각 플레이어는 1 개의 2 개 또는 3 개의 돌만 제거 할 수 있습니다 (클래식 게임에서와 같이 많은 돌은 아닙니다). 누가 이길 것인지 예측할 수 있습니까?
예, Sprague-Grundy 정리를 사용하여 우승자를 예측할 수 있습니다.

Sprague-Grundy 정리 란 무엇입니까?  
N 하위 게임과 두 명의 플레이어 A와 B로 구성된 복합 게임 (하나 이상의 서브 게임)이 있다고 가정 해 봅시다. 그런 다음 Sprague Grundy Theorem은 A와 B가 모두 최적으로 플레이하면 (즉, 실수를하지 않으면) 게임 시작시 각 하위 지위에서 Grundy 숫자의 XOR이 Zero가 아닌 경우 승리를 보장한다고 말합니다. 그렇지 않으면 XOR이 0으로 평가되면 플레이어 A는 무엇이든 상관없이 분명히 잃게됩니다.

문자열 java의 하위 문자열

Sprague Grundy 정리를 적용하는 방법?  
우리는 Sprague-Grundy 정리를 어떤 사람에게도 적용 할 수 있습니다 공정한 게임 그리고 그것을 해결하십시오. 기본 단계는 다음과 같이 나열됩니다. 



  1. 복합 게임을 하위 게임으로 나눕니다.
  2. 그런 다음 각 하위 게임에 대해 해당 위치에서 Grundy 번호를 계산합니다.
  3. 그런 다음 계산 된 모든 Grundy 숫자의 XOR을 계산하십시오.
  4. XOR 값이 0이 아닌 경우, 턴을 할 선수 (첫 번째 플레이어)는 다른 승리를 거두게됩니다.

예제 게임 : 이 게임은 3 개의 4 및 5 개의 돌을 가진 3 개의 더미로 시작하며, 움직일 플레이어는 더미에서 더 많은 양의 돌을 가진 경우에만 3 개의 돌을 3까지 가져갈 수 있습니다. 마지막으로 이동 한 플레이어가 승리합니다. 두 선수가 최적으로 플레이한다고 가정하면 어느 선수가 게임에서 승리합니까?

Sprague-Grundy 정리를 적용하여 누가 이길 것인지 말하는 방법은 무엇입니까?  
우리가 볼 수 있듯이이 게임 자체는 여러 하위 게임으로 구성되어 있습니다. 
첫 번째 단계 : 하위 게임은 각 더미로 간주 될 수 있습니다. 
두 번째 단계 : 우리는 아래 표에서 그것을 봅니다 

Grundy(3) = 3 Grundy(4) = 0 Grundy(5) = 1 

Sprague -Grundy 정리' src='//techcodeview.com/img/combinatorial/87/combinatorial-game-theory-set-4-sprague-grundy-theorem.webp' title=

푸시용 git 명령

우리는 이미이 게임의 Grundy 번호를 계산하는 방법을 이미 보았습니다. 이전의 기사.
세 번째 단계 : 3 0 1 = 2의 XOR
네 번째 단계 : XOR은 0이 아닌 숫자이므로 첫 번째 플레이어가 이길 것이라고 말할 수 있습니다.

아래는 4 단계 이상을 구현하는 프로그램입니다. 

C++
/* Game Description-  'A game is played between two players and there are N piles  of stones such that each pile has certain number of stones.  On his/her turn a player selects a pile and can take any  non-zero number of stones upto 3 (i.e- 123)  The player who cannot move is considered to lose the game  (i.e. one who take the last stone is the winner).  Can you find which player wins the game if both players play  optimally (they don't make any mistake)? '  A Dynamic Programming approach to calculate Grundy Number  and Mex and find the Winner using Sprague - Grundy Theorem. */ #include   using namespace std; /* piles[] -> Array having the initial count of stones/coins  in each piles before the game has started.  n -> Number of piles  Grundy[] -> Array having the Grundy Number corresponding to  the initial position of each piles in the game  The piles[] and Grundy[] are having 0-based indexing*/ #define PLAYER1 1 #define PLAYER2 2 // A Function to calculate Mex of all the values in that set int calculateMex(unordered_set<int> Set) {  int Mex = 0;  while (Set.find(Mex) != Set.end())  Mex++;  return (Mex); } // A function to Compute Grundy Number of 'n' int calculateGrundy(int n int Grundy[]) {  Grundy[0] = 0;  Grundy[1] = 1;  Grundy[2] = 2;  Grundy[3] = 3;  if (Grundy[n] != -1)  return (Grundy[n]);  unordered_set<int> Set; // A Hash Table  for (int i=1; i<=3; i++)  Set.insert (calculateGrundy (n-i Grundy));  // Store the result  Grundy[n] = calculateMex (Set);  return (Grundy[n]); } // A function to declare the winner of the game void declareWinner(int whoseTurn int piles[]  int Grundy[] int n) {  int xorValue = Grundy[piles[0]];  for (int i=1; i<=n-1; i++)  xorValue = xorValue ^ Grundy[piles[i]];  if (xorValue != 0)  {  if (whoseTurn == PLAYER1)  printf('Player 1 will winn');  else  printf('Player 2 will winn');  }  else  {  if (whoseTurn == PLAYER1)  printf('Player 2 will winn');  else  printf('Player 1 will winn');  }  return; } // Driver program to test above functions int main() {  // Test Case 1  int piles[] = {3 4 5};  int n = sizeof(piles)/sizeof(piles[0]);  // Find the maximum element  int maximum = *max_element(piles piles + n);  // An array to cache the sub-problems so that  // re-computation of same sub-problems is avoided  int Grundy[maximum + 1];  memset(Grundy -1 sizeof (Grundy));  // Calculate Grundy Value of piles[i] and store it  for (int i=0; i<=n-1; i++)  calculateGrundy(piles[i] Grundy);  declareWinner(PLAYER1 piles Grundy n);  /* Test Case 2  int piles[] = {3 8 2};  int n = sizeof(piles)/sizeof(piles[0]);  int maximum = *max_element (piles piles + n);  // An array to cache the sub-problems so that  // re-computation of same sub-problems is avoided  int Grundy [maximum + 1];  memset(Grundy -1 sizeof (Grundy));  // Calculate Grundy Value of piles[i] and store it  for (int i=0; i<=n-1; i++)  calculateGrundy(piles[i] Grundy);  declareWinner(PLAYER2 piles Grundy n); */  return (0); } 
Java
import java.util.*; /* Game Description- 'A game is played between two players and there are N piles of stones such that each pile has certain number of stones. On his/her turn a player selects a pile and can take any non-zero number of stones upto 3 (i.e- 123) The player who cannot move is considered to lose the game (i.e. one who take the last stone is the winner). Can you find which player wins the game if both players play optimally (they don't make any mistake)? ' A Dynamic Programming approach to calculate Grundy Number and Mex and find the Winner using Sprague - Grundy Theorem. */ class GFG {   /* piles[] -> Array having the initial count of stones/coins  in each piles before the game has started. n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to  the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ static int PLAYER1 = 1; static int PLAYER2 = 2; // A Function to calculate Mex of all the values in that set static int calculateMex(HashSet<Integer> Set) {  int Mex = 0;  while (Set.contains(Mex))  Mex++;  return (Mex); } // A function to Compute Grundy Number of 'n' static int calculateGrundy(int n int Grundy[]) {  Grundy[0] = 0;  Grundy[1] = 1;  Grundy[2] = 2;  Grundy[3] = 3;  if (Grundy[n] != -1)  return (Grundy[n]);  // A Hash Table  HashSet<Integer> Set = new HashSet<Integer>();   for (int i = 1; i <= 3; i++)  Set.add(calculateGrundy (n - i Grundy));  // Store the result  Grundy[n] = calculateMex (Set);  return (Grundy[n]); } // A function to declare the winner of the game static void declareWinner(int whoseTurn int piles[]  int Grundy[] int n) {  int xorValue = Grundy[piles[0]];  for (int i = 1; i <= n - 1; i++)  xorValue = xorValue ^ Grundy[piles[i]];  if (xorValue != 0)  {  if (whoseTurn == PLAYER1)  System.out.printf('Player 1 will winn');  else  System.out.printf('Player 2 will winn');  }  else  {  if (whoseTurn == PLAYER1)  System.out.printf('Player 2 will winn');  else  System.out.printf('Player 1 will winn');  }  return; } // Driver code public static void main(String[] args)  {    // Test Case 1  int piles[] = {3 4 5};  int n = piles.length;  // Find the maximum element  int maximum = Arrays.stream(piles).max().getAsInt();  // An array to cache the sub-problems so that  // re-computation of same sub-problems is avoided  int Grundy[] = new int[maximum + 1];  Arrays.fill(Grundy -1);  // Calculate Grundy Value of piles[i] and store it  for (int i = 0; i <= n - 1; i++)  calculateGrundy(piles[i] Grundy);  declareWinner(PLAYER1 piles Grundy n);  /* Test Case 2  int piles[] = {3 8 2};  int n = sizeof(piles)/sizeof(piles[0]);  int maximum = *max_element (piles piles + n);  // An array to cache the sub-problems so that  // re-computation of same sub-problems is avoided  int Grundy [maximum + 1];  memset(Grundy -1 sizeof (Grundy));  // Calculate Grundy Value of piles[i] and store it  for (int i=0; i<=n-1; i++)  calculateGrundy(piles[i] Grundy);  declareWinner(PLAYER2 piles Grundy n); */  } }  // This code is contributed by PrinciRaj1992 
Python3
''' Game Description-   'A game is played between two players and there are N piles   of stones such that each pile has certain number of stones.   On his/her turn a player selects a pile and can take any   non-zero number of stones upto 3 (i.e- 123)   The player who cannot move is considered to lose the game   (i.e. one who take the last stone is the winner).   Can you find which player wins the game if both players play   optimally (they don't make any mistake)? '     A Dynamic Programming approach to calculate Grundy Number   and Mex and find the Winner using Sprague - Grundy Theorem.    piles[] -> Array having the initial count of stones/coins   in each piles before the game has started.   n -> Number of piles     Grundy[] -> Array having the Grundy Number corresponding to   the initial position of each piles in the game     The piles[] and Grundy[] are having 0-based indexing''' PLAYER1 = 1 PLAYER2 = 2 # A Function to calculate Mex of all # the values in that set  def calculateMex(Set): Mex = 0; while (Mex in Set): Mex += 1 return (Mex) # A function to Compute Grundy Number of 'n'  def calculateGrundy(n Grundy): Grundy[0] = 0 Grundy[1] = 1 Grundy[2] = 2 Grundy[3] = 3 if (Grundy[n] != -1): return (Grundy[n]) # A Hash Table  Set = set() for i in range(1 4): Set.add(calculateGrundy(n - i Grundy)) # Store the result  Grundy[n] = calculateMex(Set) return (Grundy[n]) # A function to declare the winner of the game  def declareWinner(whoseTurn piles Grundy n): xorValue = Grundy[piles[0]]; for i in range(1 n): xorValue = (xorValue ^ Grundy[piles[i]]) if (xorValue != 0): if (whoseTurn == PLAYER1): print('Player 1 will winn'); else: print('Player 2 will winn'); else: if (whoseTurn == PLAYER1): print('Player 2 will winn'); else: print('Player 1 will winn'); # Driver code if __name__=='__main__': # Test Case 1  piles = [ 3 4 5 ] n = len(piles) # Find the maximum element  maximum = max(piles) # An array to cache the sub-problems so that  # re-computation of same sub-problems is avoided  Grundy = [-1 for i in range(maximum + 1)]; # Calculate Grundy Value of piles[i] and store it  for i in range(n): calculateGrundy(piles[i] Grundy); declareWinner(PLAYER1 piles Grundy n);    ''' Test Case 2   int piles[] = {3 8 2};   int n = sizeof(piles)/sizeof(piles[0]);       int maximum = *max_element (piles piles + n);     // An array to cache the sub-problems so that   // re-computation of same sub-problems is avoided   int Grundy [maximum + 1];   memset(Grundy -1 sizeof (Grundy));     // Calculate Grundy Value of piles[i] and store it   for (int i=0; i<=n-1; i++)   calculateGrundy(piles[i] Grundy);     declareWinner(PLAYER2 piles Grundy n); ''' # This code is contributed by rutvik_56 
C#
using System; using System.Linq; using System.Collections.Generic; /* Game Description- 'A game is played between two players and there are N piles of stones such that each pile has certain number of stones. On his/her turn a player selects a pile and can take any non-zero number of stones upto 3 (i.e- 123) The player who cannot move is considered to lose the game (i.e. one who take the last stone is the winner). Can you find which player wins the game if both players play optimally (they don't make any mistake)? ' A Dynamic Programming approach to calculate Grundy Number and Mex and find the Winner using Sprague - Grundy Theorem. */ class GFG  {   /* piles[] -> Array having the initial count of stones/coins  in each piles before the game has started. n -> Number of piles Grundy[] -> Array having the Grundy Number corresponding to  the initial position of each piles in the game The piles[] and Grundy[] are having 0-based indexing*/ static int PLAYER1 = 1; //static int PLAYER2 = 2; // A Function to calculate Mex of all the values in that set static int calculateMex(HashSet<int> Set) {  int Mex = 0;  while (Set.Contains(Mex))  Mex++;  return (Mex); } // A function to Compute Grundy Number of 'n' static int calculateGrundy(int n int []Grundy) {  Grundy[0] = 0;  Grundy[1] = 1;  Grundy[2] = 2;  Grundy[3] = 3;  if (Grundy[n] != -1)  return (Grundy[n]);  // A Hash Table  HashSet<int> Set = new HashSet<int>();   for (int i = 1; i <= 3; i++)  Set.Add(calculateGrundy (n - i Grundy));  // Store the result  Grundy[n] = calculateMex (Set);  return (Grundy[n]); } // A function to declare the winner of the game static void declareWinner(int whoseTurn int []piles  int []Grundy int n) {  int xorValue = Grundy[piles[0]];  for (int i = 1; i <= n - 1; i++)  xorValue = xorValue ^ Grundy[piles[i]];  if (xorValue != 0)  {  if (whoseTurn == PLAYER1)  Console.Write('Player 1 will winn');  else  Console.Write('Player 2 will winn');  }  else  {  if (whoseTurn == PLAYER1)  Console.Write('Player 2 will winn');  else  Console.Write('Player 1 will winn');  }  return; } // Driver code static void Main()  {    // Test Case 1  int []piles = {3 4 5};  int n = piles.Length;  // Find the maximum element  int maximum = piles.Max();  // An array to cache the sub-problems so that  // re-computation of same sub-problems is avoided  int []Grundy = new int[maximum + 1];  Array.Fill(Grundy -1);  // Calculate Grundy Value of piles[i] and store it  for (int i = 0; i <= n - 1; i++)  calculateGrundy(piles[i] Grundy);  declareWinner(PLAYER1 piles Grundy n);    /* Test Case 2  int piles[] = {3 8 2};  int n = sizeof(piles)/sizeof(piles[0]);  int maximum = *max_element (piles piles + n);  // An array to cache the sub-problems so that  // re-computation of same sub-problems is avoided  int Grundy [maximum + 1];  memset(Grundy -1 sizeof (Grundy));  // Calculate Grundy Value of piles[i] and store it  for (int i=0; i<=n-1; i++)  calculateGrundy(piles[i] Grundy);  declareWinner(PLAYER2 piles Grundy n); */  } }  // This code is contributed by mits 
JavaScript
<script> /* Game Description- 'A game is played between two players and there are N piles of stones such that each pile has certain number of stones. On his/her turn a player selects a pile and can take any non-zero number of stones upto 3 (i.e- 123) The player who cannot move is considered to lose the game (i.e. one who take the last stone is the winner). Can you find which player wins the game if both players play optimally (they don't make any mistake)? '   A Dynamic Programming approach to calculate Grundy Number and Mex and find the Winner using Sprague - Grundy Theorem. */ /* piles[] -> Array having the initial count of stones/coins  in each piles before the game has started. n -> Number of piles   Grundy[] -> Array having the Grundy Number corresponding to  the initial position of each piles in the game   The piles[] and Grundy[] are having 0-based indexing*/ let PLAYER1 = 1; let PLAYER2 = 2; // A Function to calculate Mex of all the values in that set function calculateMex(Set) {  let Mex = 0;    while (Set.has(Mex))  Mex++;    return (Mex); } // A function to Compute Grundy Number of 'n' function calculateGrundy(nGrundy) {  Grundy[0] = 0;  Grundy[1] = 1;  Grundy[2] = 2;  Grundy[3] = 3;    if (Grundy[n] != -1)  return (Grundy[n]);    // A Hash Table  let Set = new Set();    for (let i = 1; i <= 3; i++)  Set.add(calculateGrundy (n - i Grundy));    // Store the result  Grundy[n] = calculateMex (Set);    return (Grundy[n]); } // A function to declare the winner of the game function declareWinner(whoseTurnpilesGrundyn) {  let xorValue = Grundy[piles[0]];    for (let i = 1; i <= n - 1; i++)  xorValue = xorValue ^ Grundy[piles[i]];    if (xorValue != 0)  {  if (whoseTurn == PLAYER1)  document.write('Player 1 will win  
'
); else document.write('Player 2 will win
'
); } else { if (whoseTurn == PLAYER1) document.write('Player 2 will win
'
); else document.write('Player 1 will win
'
); } return; } // Driver code // Test Case 1 let piles = [3 4 5]; let n = piles.length; // Find the maximum element let maximum = Math.max(...piles) // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided let Grundy = new Array(maximum + 1); for(let i=0;i<maximum+1;i++) Grundy[i]=0; // Calculate Grundy Value of piles[i] and store it for (let i = 0; i <= n - 1; i++) calculateGrundy(piles[i] Grundy); declareWinner(PLAYER1 piles Grundy n); /* Test Case 2 int piles[] = {3 8 2}; int n = sizeof(piles)/sizeof(piles[0]); int maximum = *max_element (piles piles + n); // An array to cache the sub-problems so that // re-computation of same sub-problems is avoided int Grundy [maximum + 1]; memset(Grundy -1 sizeof (Grundy)); // Calculate Grundy Value of piles[i] and store it for (int i=0; i<=n-1; i++) calculateGrundy(piles[i] Grundy); declareWinner(PLAYER2 piles Grundy n); */ // This code is contributed by avanitrachhadiya2155 </script>

출력 :  

tkinter 버튼
Player 1 will win

시간 복잡성 : O (n^2) 여기서 n은 파일의 최대 석수 수입니다. 

공간 복잡성 : o (n) Grundy 어레이는 중복 계산을 피하기 위해 하위 문제의 결과를 저장하는 데 사용되며 O (n) 공간이 필요합니다.

참조 :  
https://en.wikipedia.org/wiki/sprague%E2%80%93grundy_theorem

독자에게 운동 : 아래 게임을 고려하십시오. 
N 정수 A1 A2 .. An. 자신의 턴에서 플레이어는 정수를 선택합니다. 정수를 2 3 또는 6으로 나눈 다음 바닥을 가져갑니다. 정수가 0이되면 제거됩니다. 마지막으로 이동 한 플레이어가 승리합니다. 두 선수가 최적으로 플레이한다면 어느 선수가 게임에서 이기는가?
힌트 : 예제 3을 참조하십시오 이전의 기사.