Either you know the optimal NIM strategy or you don't. I guess you're supposed to Google NIM and read the optimal solution. I tried to use my brain instead, and that was a failing endeavor. There's no way I was deriving the Sprague-Grundy theorem while doing a Topcoder problem. So it goes.
So, I'll tell you the Sprague-Grundy theorem as is applies to this problem, and let you think about a solution: If the XOR of all of the pile sizes is zero, then you are in a losing position. It's an if-and-only-if. So, here are some losing positions:
So what I'll do now is let you think about and solve the problem, which I'll state formally:
This will work, because (xi XOR S) will have an even number of highest bits, so the highest bit will equal zero. Therefore, (xi XOR S) has to be less than xi.
The highest number allowed is 737,373,737, which is 0x2bf36e29, which is between (1 << 29) and (1 << 30). So, my highest bit should be in position 28, because all numbers that start with that bit will be less than 0x20000000. My first thought was to have:
xi = (1 << 28) | (1 << i).
xi = (1 << 20) | (1 << (19-i/2)) | (i%2).
When n is 5, for example, that gives you the following values (in binary);
11000000000000000000 11000000000000000001 10100000000000000000 10100000000000000001 10010000000000000000Since n is odd, it's clear that S won't equal zero, so this works.
When n is even, do the same thing, but have xn-1 equal one.
If you want to double-check yourself, here are the answers for examples 0, 1, 2 and 3. For example 3, I've made n equal to 10:
UNIX> a.out 0 1572864 UNIX> a.out 1 1572864 1 UNIX> a.out 2 1572864 1572865 1310720 UNIX> a.out 3 1572864 1572865 1310720 1310721 1179648 1179649 1114112 1114113 1081344 1 UNIX>