In this HackerRank Unfair Game problem solution, You are playing a game of Nim with a friend. The rules are are follows:

  1. Initially, there are N piles of stones. Two players play alternately.
  2. In each turn, a player can choose one nonempty pile and remove any number of stones from it. At least one stone must be removed.
  3. The player who picks the last stone from the last nonempty pile wins the game.

It is currently your friend's turn. You suddenly realize that if your friend was to play optimally in that position, you would lose the game. So while he is not looking, you decide to cheat and add some (possibly 0) stones to each pile. You want the resultant position to be such that your friend has no guaranteed winning strategy, even if plays optimally. You cannot create a new pile of stones. You can only add stones, and not remove stones from a pile. What is the least number of stones you need to add?

HackerRank Unfair Game problem solution


Problem solution in Python.

import operator
from functools import reduce

def xor(nums):
    return reduce(operator.xor, nums, 0)

def lowZero(v):
    p = 0
    while True:
        m = 1 << p
        if v & m == 0:
            return p
        p += 1

def highOne(v):
    p = 0
    high = None
    while v != 0:
        m = 1 << p
        if v & m != 0:
            high = p
            v &= ~m
        p += 1
    return high

def zeroAt(v, p):
    return v & (1 << p) == 0

def diffToFlip(v, p):
    t = 1 << p
    r = (v + t) & ~(t - 1)
    return r - v

def lowPosWithMoreThanOneZero(nums):
    p = 0
    while True:
        m = 1 << p
        n = sum(1 if v & m == 0 else 0 for v in nums)
        if n > 1:
            return p
        p += 1
    
def pairs(n):
    return ((i, j) for i in range(0, n - 1) for j in range(i + 1, n))
                    
def fixPiles(piles):
    highOneP = highOne(xor(piles))
    if highOneP == None: # the piles are in a winning position
        r = piles
    elif any(zeroAt(v, highOneP) for v in piles):
        r = fixPilesWithZeroAtHigh(piles)
    else:
        r = fixPilesWithoutZeroAtHigh(piles, highOneP)
    return r

def fixPilesWithZeroAtHigh(piles):
    piles = list(piles)
    while True:
        highOneP = highOne(xor(piles))
        if highOneP == None:
            return piles
        candidates = [(i, diffToFlip(v, highOneP)) for i, v in enumerate(piles) if zeroAt(v, highOneP)]
        winner = min(candidates, key = operator.itemgetter(1))
        i, add = winner
        piles[i] += add
    return piles

def fixPilesWithoutZeroAtHigh(piles, highOneP):
    highPiles = [v >> (highOneP + 1) for v in piles]
    highPilesZ = [(v, lowZero(v)) for v in highPiles]
    matches = [(i, j, highOneP + 1 + highPilesZ[i][1]) for i, j in pairs(len(piles)) if highPilesZ[i][1] == highPilesZ[j][1]]
    if not matches:
        zeroP = lowPosWithMoreThanOneZero(highPiles)
        lowzs = [i for i, v in enumerate(highPiles) if zeroAt(v, zeroP)]
        nz = len(lowzs)
        baseZeroP = highOneP + 1 + zeroP
        matches = [(lowzs[i], lowzs[j], baseZeroP) for i, j in pairs(nz)]
    results = (fixPilesTwoZeros(piles, zeroP, i, j) for i, j, zeroP in matches)
    return min(results, key = sum)

def fixPilesTwoZeros(piles, zeroP, i, j):
    iAdd = diffToFlip(piles[i], zeroP)
    jAdd = diffToFlip(piles[j], zeroP)
    piles = list(piles)
    piles[i] += iAdd
    piles[j] += jAdd
    return fixPilesWithZeroAtHigh(piles)

def solve(piles):
    fixedPiles = fixPiles(piles)
    return sum(fixedPiles) - sum(piles), fixedPiles

def readLine(): return input()
def readInt(): return int(readLine())
def readInts(): return tuple(int(token) for token in readLine().split())
def readIntList(): return list(readInts())

def main():
    nt = readInt()
    for _ in range(nt):
        _n = readInt()
        piles = readIntList()
        answer, _fixedPiles = solve(piles)
        print(answer)
main()


Problem solution in Java.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class UnfairGame {
    static int om(int[] values, boolean notDone) {
        int threshold = 0;
        int stones = 0;
        int nimSum = nimSum(values);
        if (nimSum == 0)
            return 0;
        int index = getIndexOfLargest(values);
        int t = values[index];
        int digits = 0;
        while (t != 0) {
            t >>= 1;
            digits++;
        }
        int[] newValues = values.clone();
        newValues[index] = 1 << digits;
        int buffer = newValues[index] - values[index];
        while (nimSum != 0) {
            int highestBit = -1;
            while (nimSum != 0) {
                nimSum >>= 1;
                highestBit++;
            }
            int required = 1 << highestBit;
            threshold = required << 1;
            int mask = required - 1;
            int least = required;
            int keyIndex = -1;
            int standby = -1;
            int atleast = required;
            for (int i = 0; i < values.length; i++) {
                int offer = required - (values[i] & mask);
                if (offer <= atleast) {
                    atleast = offer;
                    standby = i;
                }
                if (offer <= least && (offer + (values[i] & (threshold - 1))) < threshold
                        && (values[i] & required) == 0) {
                    least = offer;
                    keyIndex = i;
                }
            }
            if (keyIndex == -1) {
                stones += atleast;
                values[standby] += atleast;
            } else {
                stones += least;
                values[keyIndex] += least;
            }
            nimSum = nimSum(values);
        }
        if (stones < threshold || !notDone) {
            return stones;
        }
        int chance = om(newValues, false);
        if (buffer + chance < stones)
            return buffer + chance;
        else
            return stones;

    }

    static int nimSum(int[] values) {
        int sum = 0;
        for (int i = 0; i < values.length; i++) {
            sum ^= values[i];
        }
        return sum;
    }

    static int getIndexOfLargest(int[] values) {
        int mask = 1 << 31;
        mask--;
        return getIndexOfLargest(mask, values);
    }

    static int getIndexOfLargest(int mask, int[] values) {
        int largestIndex = 0;
        for (int i = 0; i < values.length; i++) {
            if ((values[i] & mask) > values[largestIndex])
                largestIndex = i;
        }
        return largestIndex;
    }

    static int pairs(int[] values, int bitIndex) {
        int count = 0;
        int v = 1 << bitIndex;
        for (int i = 0; i < values.length; i++) {
            if ((values[i] & v) > 0)
                count++;
        }
        return count;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        int T = Integer.parseInt(s);
        for (int i = 0; i < T; i++) {
            s = br.readLine();
            int N = Integer.parseInt(s);
            s = br.readLine();
            String[] ss = s.split("\\s");
            int[] values = new int[N];
            for (int j = 0; j < N; j++) {
                values[j] = Integer.parseInt(ss[j]);
            }
            System.out.println(om(values,true));
        }

    }
}


Problem solution in C++.

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

#define REP(i,n) for(int (i)=0,_n=(n);(i)<_n;(i)++)
#define FOR(i,a,b) for(int (i)=(a),_n=(b);(i)<=_n;(i)++)
#define FORD(i,a,b) for(int (i)=(a),_n=(b);(i)>=_n;(i)--)

typedef long long LL;

const LL inf = 0x7ffffffffffffffLL;

int main()
{
	int T;
	scanf( "%d", &T );
	while ( T-- ) {
		int n;
		LL  ts[20];
		scanf( "%d", &n );
		REP(i,n) cin >> ts[i];
		LL  ans = inf;


		REP(bit,1<<n) {
			LL s[20];
			REP(i,n) s[i] = ts[i];
			
			LL tans = 0;
			FORD(x,40,0) {
				bool odd = false;
				REP(i,n) if ( s[i] & (1LL << x) ) odd = !odd;
				if ( !odd ) continue;
				
				if ( __builtin_popcount(bit) <= 1 ) goto done;

				int choose = 0;
				LL  cost   = inf;
				LL  value  = 1LL << x;
				LL  mask   = value - 1;
				REP(i,n) if ( (bit & (1 << i)) && !(s[i] & (1LL << x)) && value - (s[i] & mask) < cost ) 
					cost = value - (s[i] & mask), choose = i;

				if ( cost == inf ) {
					do {
						x++;
						value = 1LL << x;
						mask  = value - 1;
						REP(i,n) if ( (bit & (1 << i)) && !(s[i] & (1LL << x)) && value - (s[i] & mask) < cost )
							cost = value - (s[i] & mask), choose = i;
						if ( cost == inf ) continue;
						s[choose] = (s[choose] & ~mask) | (1LL << x);
						tans += cost;
						break;
					} while ( true );
					x++;
				}
				else {
					s[choose] = (s[choose] & ~mask) | (1LL << x);
					tans += cost;
				}
			}
			ans = min(ans,tans);
			done:;
		}
		cout << ans << endl;
	}
	return 0;
}


Problem solution in C.

#include <stdio.h>
#include <stdlib.h>
long long min(long long x,long long y);
int counti(int i);
int mask[31],count[32768];
long long dp[32][32768];

int main(){
  int T,N,x,i,j,k,l;
  long long ans;
  for(i=0;i<32768;i++)
    count[i]=counti(i);
  scanf("%d",&T);
  while(T--){
    for(i=0;i<31;i++)
      mask[i]=0;
    for(i=0;i<32;i++)
      for(j=0;j<32768;j++)
        dp[i][j]=-1;
    dp[31][0]=0;
    scanf("%d",&N);
    for(i=0;i<N;i++){
      scanf("%d",&x);
      for(j=0;j<31;mask[j]|=((x&1)<<i),j++,x>>=1);
    }
    for(i=30;i>=0;i--)
      for(j=0;j<(1<<N);j++)
        if(dp[i+1][j]!=-1){
          if(!j && i && (count[mask[i-1]]==N || count[mask[i-1]]==N-1) && N%2 && count[mask[i]]<N-1 && count[mask[i]]%2==0)
            for(k=0;k<N-1;k++)
              for(l=k+1;l<N;l++){
                if(!(mask[i]&(1<<k)) && !(mask[i]&(1<<l)))
                  dp[i][(1<<k)|(1<<l)]=min(dp[i][(1<<k)|(1<<l)],dp[i+1][j]+2*(1LL<<i));
              }
          if(count[mask[i]&(~j)]%2){
            ans=dp[i+1][j]-(count[mask[i]&j]-1)*(1LL<<i);
            for(k=0;k<N;k++)
              if(j&(1<<k) || !(mask[i]&(1<<k)))
                dp[i][j|(1<<k)]=min(dp[i][j|(1<<k)],ans);
          }
          else
            dp[i][j]=min(dp[i][j],dp[i+1][j]-count[mask[i]&j]*(1LL<<i));
        }
    for(i=0,ans=-1;i<(1<<N);i++)
      ans=min(ans,dp[0][i]);
    printf("%lld\n",ans);
  }
  return 0;
}
long long min(long long x,long long y){
  if(x==-1)
    return y;
  if(y==-1)
    return x;
  return (x<y)?x:y;
}
int counti(int i){
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}