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 :
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
Kitty's Calculations on a Tree
Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a
View Solution →Is This a Binary Search Tree?
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a
View Solution →Square-Ten Tree
The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the
View Solution →Balanced Forest
Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a
View Solution →Jenny's Subtrees
Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .
View Solution →Tree Coordinates
We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For
View Solution →