Stone Game


Problem Statement :


Alice and Bob are playing the game of Nim with  piles of stones with sizes . If Alice plays first, she loses if and only if the 'xor sum' (or 'Nim sum') of the piles is zero, i.e., .

Since Bob already knows who will win (assuming optimal play), he decides to cheat by removing some stones in some piles before the game starts. However, to reduce the risk of suspicion, he must keep at least one pile unchanged. Your task is to count the number of ways Bob can remove the stones to force Alice into losing the game. Since the number can be very large, output the number of ways modulo . Assume that both players will try to optimize their strategy and try to win the game.

Input Format

The first line of the input contains an integer  denoting the number of piles. The next line contains  space-separated integers  indicating the sizes of the stone piles.

Output Format

Print a single integer denoting the number of ways Bob can force Alice to lose the game, modulo .



Solution :



title-img


                            Solution in C :

In  C  :







#include <stdio.h>

#define P 1000000007LL

long long a[200][2][2][2],i,j,k,l,m[100],n,v,b[200],x,t, im[100];

long long poww(long long xx, long long nn)
{
long long zz,vv;

vv = 1;
zz = xx;

while(nn)
{
if(nn&1) vv = (vv*zz)%P;
zz = (zz*zz)%P;
nn/=2;
}

return vv;
}


int main()
{

scanf("%lld",&n);
for(i=0;i<n;i++) scanf("%lld",b+i);

m[0] = 1;
im[0] = 1;
for(i=1;i<=60;i++) 
  {
   m[i] = 2*m[i-1];
   im[i] = poww(m[i], P-2);
 
// printf("%lld %lld %lld\n", m[i],im[i], (m[i]*im[i])%P);
  }

//return 0;

x = 0;
for(i = 0; i<n ;i++) x^=b[i];

//printf("%lld = x\n", x);

k = 40;

v = 0;

if(x==0) v++;


while(k>=0)
{

//printf("---- k = %lld ---%lld---\n",k,v);

a[0][0][0][0] = 0;
a[0][0][0][1] = 0;

if(m[k]&b[0])
  a[0][0][0][1] = ((m[k]-1)&b[0]);
else  
  a[0][0][0][0] = ((m[k]-1)&b[0]);


a[0][0][1][0] = 0;
a[0][0][1][1] = 0;

if(b[0]&m[k])
     a[0][0][1][0] = m[k];

a[0][1][0][0] = 0;
a[0][1][0][1] = 0;

if(b[0]&m[k])
  a[0][1][0][1] = 1;
else
  a[0][1][0][0] = 1;  

a[0][1][1][0] = 0;
a[0][1][1][1] = 0;

i = 0;
/*
for(j=0;j<2;j++)
 for(l=0;l<2;l++)
  for(t=0;t<2;t++)
   printf("i=%lld %lld %lld %lld -> %lld\n",i,j,l,t,a[i][j][l][t]);
*/

for(i=1; i<n; i++)
 {

//printf("%lld %lld -> %lld\n", b[i],m[k],b[i]&m[k]);

//ma k-ty bit
if(b[i]&m[k])
{
//printf("s najvyssim bitom\n");

 a[i][0][0][0] = (a[i-1][0][0][1]*((m[k]-1) & b[i]))%P;
 a[i][0][0][1] = (a[i-1][0][0][0]*((m[k]-1) & b[i]))%P; 
 

//nemazu najvyssi bit
 a[i][0][1][0] = (a[i-1][0][1][1]*((m[k]-1) & b[i]))%P;    
 a[i][0][1][1] = (a[i-1][0][1][0]*((m[k]-1) & b[i]))%P;    

//printf("1) %lld\n", (a[i-1][0][1][0]*((m[k]-1) & b[i]))%P);    


//mazu najvyssi bit
 a[i][0][1][0] = (a[i][0][1][0] + a[i-1][0][1][0]*m[k])%P;    
 a[i][0][1][1] = (a[i][0][1][1] + a[i-1][0][1][1]*m[k])%P;    


 a[i][0][1][0] = (a[i][0][1][0] + a[i-1][0][0][0]*m[k])%P;
 a[i][0][1][1] = (a[i][0][1][1] + a[i-1][0][0][1]*m[k])%P;

// a[i][0][1][0] = (a[i][0][1][0] + a[i-1][0][0][0])%P;
// a[i][0][1][1] = (a[i][0][1][1] + a[i-1][0][0][1])%P;
 

 a[i][1][0][0] = (a[i-1][1][0][1] * (((m[k]-1)&b[i])+1))%P;
 a[i][1][0][1] = (a[i-1][1][0][0] * (((m[k]-1)&b[i])+1))%P;
 
 a[i][1][0][0] = (a[i][1][0][0] + a[i-1][0][0][1])%P;
 a[i][1][0][1] = (a[i][1][0][1] + a[i-1][0][0][0])%P;

 a[i][1][1][0] = (a[i-1][1][1][0]*m[k])%P;
 a[i][1][1][1] = (a[i-1][1][1][1]*m[k])%P;

//printf("-1. %lld\n",(a[i-1][1][1][0]*m[k])%P);


 a[i][1][1][0] = (a[i][1][1][0] + a[i-1][1][1][1]*(((m[k]-1)&b[i])+1))%P;
 a[i][1][1][1] = (a[i][1][1][1] + a[i-1][1][1][0]*(((m[k]-1)&b[i])+1))%P;

// printf("%lld...\n", (a[i-1][1][1][0]*(((m[k]-1)&b[i])+1))%P);
//printf("-2. %lld\n",(a[i-1][1][1][1]*(((m[k]-1)&b[i])+1))%P);


 //prvy co sa nemeni
 a[i][1][1][0] = (a[i][1][1][0] + a[i-1][0][1][1])%P;
 a[i][1][1][1] = (a[i][1][1][1] + a[i-1][0][1][0])%P;

//printf("-3. %lld\n",a[i-1][0][1][1]);

 
 //prvy co si maze najvyssi bit 
 a[i][1][1][0] = (a[i][1][1][0] + a[i-1][1][0][0]*m[k])%P;
 a[i][1][1][1] = (a[i][1][1][1] + a[i-1][1][0][1]*m[k])%P;

// a[i][1][1][0] = (a[i][1][1][0] + a[i-1][1][0][0])%P;
// a[i][1][1][1] = (a[i][1][1][1] + a[i-1][1][0][1])%P;

// printf("%lld,,\n",(a[i-1][1][1][1]*m[k])%P);
//printf("-4. %lld\n",a[i-1][1][0][0]);

} 
else 
{
//printf("bez najvyssieho bitu\n");

 a[i][0][0][0] = (a[i-1][0][0][0]*((m[k]-1) & b[i]))%P;
 a[i][0][0][1] = (a[i-1][0][0][1]*((m[k]-1) & b[i]))%P; 
 

//nemazu najvyssi bit
 a[i][0][1][0] = (a[i-1][0][1][0]*((m[k]-1) & b[i]))%P;    
 a[i][0][1][1] = (a[i-1][0][1][1]*((m[k]-1) & b[i]))%P;    

 a[i][1][0][0] = (a[i-1][1][0][0] * (((m[k]-1)&b[i])+1))%P;
 a[i][1][0][1] = (a[i-1][1][0][1] * (((m[k]-1)&b[i])+1))%P;
 
 a[i][1][0][0] = (a[i][1][0][0] + a[i-1][0][0][0])%P;
 a[i][1][0][1] = (a[i][1][0][1] + a[i-1][0][0][1])%P;


 a[i][1][1][0] = (a[i-1][1][1][0]*(((m[k]-1)&b[i])+1))%P;
 a[i][1][1][1] = (a[i-1][1][1][1]*(((m[k]-1)&b[i])+1))%P;

 //prvy co sa nemeni
 a[i][1][1][0] = (a[i][1][1][0] + a[i-1][0][1][0])%P;
 a[i][1][1][1] = (a[i][1][1][1] + a[i-1][0][1][1])%P;
} 
/*
for(j=0;j<2;j++)
 for(l=0;l<2;l++)
  for(t=0;t<2;t++)
   printf("i=%lld %lld %lld %lld -> %lld\n",i,j,l,t,a[i][j][l][t]);
*/
}

v = (v + a[n-1][1][1][0]*im[k])%P;


if(x & m[k]) break;
k--;

//break;
}


printf("%lld\n",v);

return 0;
}
                        


                        Solution in C++ :

In  C ++ :







#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

const long long modulo = 1e9 + 7;

int a[128], SIZE;

void scan(){
  cin >> SIZE;
  
  for ( int i = 0; i < SIZE; ++i )
    cin >> a[i];
}

vector < int > v;
int N;

int highestBit ( int X ){
    int p = 1, ret = 0;

    while ( p <= X ){
        if ( p & X )
            ret = p;
        p *= 2;
    }

    return ret;
}
long long go(){
    long long dp[128][2];
    memset ( dp, 0, sizeof ( dp ) );
    dp[0][0] = 1;
    int T = highestBit( v.back() );
    if ( highestBit ( N ) > T )
        return 0;
    for ( int i = 0; i < (int)v.size() - 1; ++i )
        for ( int Bit = 0; Bit < 2; ++Bit ){
            if ( v[i] >= T )
                dp[i + 1][Bit ^ 1] += ( dp[i][Bit] * ( v[i] - T + 1 ) ) % modulo;
            dp[i + 1][Bit] += ( dp[i][Bit] * (long long)min ( v[i] + 1, T ) ) %modulo;
        }

    if ( N & T )
        return dp[(int)v.size() - 1][1];
    return dp[(int)v.size() - 1][0];


}
int go( vector <int> cards) {
    if ( cards.size() == 1 )
	return cards[0] >= 0;
    v = cards;
    N = 0;
    sort ( v.begin(), v.end() );
    long long res = 0;
    
    while ( v.back() ){
	res = ( res + go() ) % modulo;
	int X = highestBit ( v.back() );
	v.back() ^= X;
	N ^= X;
	sort ( v.begin(), v.end() );
    }

    return res + (!N);
}

void solve(){
  vector <int> v;
  
  for ( int i = 0; i < SIZE; ++i )
    v.push_back ( a[i] );
  
  long long res = go ( v );
  
  for ( int i = 0; i < SIZE; ++i )
    --v[i];
  
  res = ( res + modulo - go ( v ) ) % modulo;
  
  cout << res << endl;
  
}
int main(){
  
  scan();
  solve();
}
                    


                        Solution in Java :

In  Java :









import java.io.*;

import java.math.BigDecimal;
import java.util.*;

public class Solution {

    void solve()throws Exception
    {

        int testCases=1;
        for(int test=1;test<=testCases;test++)
        {
            solveTestCase(test);
        }

    }

    final static long mod=1000000007;
    private void solveTestCase(int testNumber)throws Exception{
        int n=nextInt();
        int[]a=new int[n];
        for(int i=0;i<n;i++)
            a[i]=nextInt();
        long res=doIt(a);
        for(int i=0;i<n;i++)
            a[i]--;

        res-=doIt(a);
        res+=mod;
        res%=mod;

        System.out.println(res);

    }

    private long doIt(int[] a) {
        int highestBit=-1;
        for(int i=0;i<a.length;i++)
        {
            if(a[i]>0)
                highestBit=Math.max(highestBit, Integer.highestOneBit(a[i]));
        }
        if(highestBit==-1)
            return 1;
        int cnt=0;
        ArrayList<Integer>list=new ArrayList<Integer>();
        long other=1;

        for(int i=0;i<a.length;i++)
        {
            if(highestBit==Integer.highestOneBit(a[i]))
                list.add(a[i]^highestBit);
            else
                other=other*(a[i]+1)%mod;
        }
        long[]dp=getDp(list,highestBit);

        long res=0;
        for(int k=1;k<dp.length;k++)
        if((list.size()-k)%2==0)
        {
            res=res+dp[k]*other;
            res%=mod;
        }
        if(list.size()%2==0)
        {
            int[]b=a.clone();
            for(int i=0;i<a.length;i++)
            {
                if(highestBit==Integer.highestOneBit(b[i]))
                    b[i]^=(highestBit);
            }
            res+=doIt(b);
            res%=mod;

        }
        return res;


    }

    private long[] getDp(ArrayList<Integer> list,int mul) {
        int[]a=new int[list.size()];
        for(int i=0;i<a.length;i++)
            a[i]=list.get(i);
        long[]dp=new long[a.length+1];
        dp[0]=1;
        for(int x: a)
        {
            long[]next=new long[dp.length];
            for(int i=0;i<dp.length;i++)
            {
                next[i]=dp[i];
                
                if(i>0)
                {
                    next[i]+=dp[i-1]*(x+1);
                    next[i]%=mod;
                }
            }
            dp=next;
        }

        long[]res=new long[dp.length];
        long v=1;
        for(int k=1;k<res.length;k++)
        {
            res[k]=dp[a.length-k]*v;
            res[k]%=mod;
            v=v*mul%mod;
        }
        return res;
    }



 
    BufferedReader reader;
    PrintWriter writer;
    StringTokenizer stk;
    void run()throws Exception
    {

        reader=new BufferedReader(new InputStreamReader(System.in));
        
        stk=null;
        writer=new PrintWriter(new PrintWriter(System.out));
      
        solve();
        reader.close();
        writer.close();
    }
    int nextInt()throws Exception
    {
        return Integer.parseInt(nextToken());
    }

    long nextLong()throws Exception
    {
        return Long.parseLong(nextToken());

    }
    double nextDouble()throws Exception
    {
        return Double.parseDouble(nextToken());


    }

    String nextString()throws Exception
    {
        return nextToken();
    }
    String nextLine()throws Exception
    {
        return reader.readLine();
    }
    String nextToken()throws Exception
    {
        if(stk==null || !stk.hasMoreTokens())
        {
            stk=new StringTokenizer(nextLine());
            return nextToken();

        }
        return stk.nextToken();
    }

    public static void main(String[]args) throws Exception
    {
        new Solution().run();
    }








}
                    


                        Solution in Python : 
                            
In Python3 :







import operator as op
import functools as ft
from sys import stderr
MOD = 1000000007

def readcase():
    npiles = int(input())
    piles = [int(fld) for fld in input().split()]
    assert npiles == len(piles)
    return piles

def numsolns(piles):
    return (numunrestrictedsolns(piles) - 
            numunrestrictedsolns([pile-1 for pile in piles if pile > 1])) % MOD

def numunrestrictedsolns(piles, MOD=MOD):
    if len(piles) == 0:
        return 1
    xorall = ft.reduce(op.xor, piles)
    leftmost = ft.reduce(op.or_, piles).bit_length() - 1
    rightmost = max(0, xorall.bit_length() - 1)
    ans = 0
    for first1 in range(rightmost, leftmost+1):
        premult = 1
        matchbit = 1 << first1
#        print('first1 =', first1, file=stderr)
        for i, bigalt in enumerate(piles):
            if bigalt & matchbit != 0:
                even = 1
                odd = 0
                for pile in piles[i+1:]:
                    neweven = (1 + (pile & ~-matchbit)) * even
                    newodd = (1 + (pile & ~-matchbit)) * odd
                    if pile & matchbit != 0:
                        neweven += matchbit * odd
                        newodd += matchbit * even
                    even, odd = neweven % MOD, newodd % MOD
#                    print(i, even, odd, ans, file=stderr)
                ans += (even if xorall & matchbit != 0 else odd) * premult % MOD
#                print(ans, premult, file=stderr)
            premult = (premult * ((bigalt & ~-matchbit) + 1)) % MOD
    if xorall == 0:
        ans += 1
    return ans % MOD

print(numsolns(readcase()))
                    


View More Similar Problems

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →