Advertisement
RaFiN_

Sprague Grundy Dividing Piles

Jul 8th, 2019
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. /* Sprague Grundy Dividing Piles */
  2.  
  3. /*********************** let the play begin() *********************************/
  4.  
  5. int gr[MAX];int ans,f[MAX],root,pre[MAX];
  6.  
  7. void grundy(int n){
  8.     int y = 0;
  9.     for(int i = 2;;i++){// Number of ways of dividing
  10.         if(i*(i-1)>=2*n)break;
  11.         int x = n - (i*(i-1))/2;
  12.         if(x%i)continue;
  13.         x/=i;
  14.         y = pre[x-1]^pre[x+i-1];
  15.         if(!y&&ans==-1&&n==root)ans = i;//if xor of second step is zero that means 1st player will win because
  16.        // cout<<y<<endl;// second player starts from 2nd step. that's why !y comes .
  17.         f[y] = n;//keep tracking the grundy values
  18.     }
  19.     int cc = 0;
  20.     while(f[cc]==n)cc++;//mex of all grundies is grundy for n
  21.     gr[n] = cc;
  22.     pre[n] = cc;
  23.     pre[n]^=pre[n-1];
  24.  
  25.  
  26. }
  27.  
  28.  
  29. int main()
  30. {
  31.     booster()
  32.     ///read("input.txt");
  33.  
  34.     int n;
  35.     cin>>n;
  36.     root = n;
  37.     ans = -1;
  38.     for(int i = 3;i<=n;i++){
  39.         grundy(i);
  40.     }
  41.     if(gr[n])cout<<ans;
  42.     else cout<<-1;
  43.  
  44.  
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement