Triple Nim
Problem Description
Alice and Bob are always playing all kinds of Nim games and Alice always goes first. Here is the rule of Nim game:
There are some distinct heaps of stones. On each turn, two players should remove at least one stone from just one heap. Two player will remove stone one after another. The player who remove the last stone of the last heap will win.
Alice always wins and Bob is very unhappy. So he decides to make a game which Alice will never win. He begins a game called “Triple Nim”, which is the Nim game with three heaps of stones. He’s good at Nim game but bad as math. With exactly N stones, how many ways can he finish his target? Both Alice and Bob will play optimally.
Input
Multiple test cases. The first line contains an integer T (T <= 100000), indicating the number of test case. Each case contains one line, an integer N (3 <= N <= 1000000000) indicating the number of stones Bob have.
Output
One line per case. The number of ways Bob can make Alice never win.
Sample Input
3 3 6 14
Sample Output
0 1 4
Hint
In the third case, Bob can make three heaps (1,6,7), (2,5,7), (3,4,7) or (3,5,6).
Source
题意:给你n个石子分成三堆,能够让先手必败的情况的种类数。。。
思路:先打表看看有什么规律,然而只打出表来看不出什么来,队友说抑或、二进制,立刻想到用二进制表示一下,瞅了半天,终于看出来,最低位为1的个数一定为0,然后一讨论,明白了,奇数一定是0,那么再把奇数排除,一眼看出了规律。。。前面1的个数就对应种类数,那样子就推了一下公式c = (3^(sum - 1) - 1)/2....
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<stack>
#define ll long long
using namespace std;
//const int maxn = 8192;
const int maxn = 100;
ll v[maxn];
string tostt(int a) {
string s; stack<int>st;
while(a) st.push(a%2), a /= 2;
while(!st.empty()) s += (st.top() + '0'), st.pop();
return s;
}
ll pow(ll a, ll b) {
ll ans = 1;
while(b){
if(b&1) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
/*
void init(){
for(int n = 3; n < maxn; n++){
if(n%2 != 0) continue;
int sum = 0;
printf("%d : ",n);
cout << tostt(n) << endl;
for(int i = 1; i <= n; i++)
for(int j = i; j <= n; j++)
for(int k = j; k <= n; k++)
if((i+j+k) == n&&(i^j^k) == 0) printf("%d %d %d\n",i,j,k),sum++;
printf(" %d\n\n", sum);
}
}
*/
int main()
{
int t, n;
string ns;
scanf("%d", &t);
while(t--){
//init();
scanf("%d", &n);
if(n%2 != 0) {
printf("0\n");continue;
}
ns = tostt(n);
int sum = 0;
for(int i = 0; i < ns.length(); i++)
if(ns[i] == '1') sum++;
printf("%lld\n",(pow((ll)3, (ll)(sum - 1)) - 1)/2);
//cout << ns << endl;
//printf("%d : %d\n",n, sum);
}
return 0;
}