山东省第七届ACM省赛 Triple Nim(Nim博弈)

13 篇文章 0 订阅
13 篇文章 0 订阅

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

题目描述

典型的Nim博弈,则需要求有多少种组合方式使得三个数之和等于n且三个数的异或值等于0.

解题思路

首先当n为奇数时,最后多出一个1 ,无论怎样分异或结果都不可能为0,所以答案为0;对于其他情况先求出n的二进制数含有多少个1,然后每一个为1 的二进制位都可以分解为较少一位的两个数相加(如8=4+4),然后将这两个数分配到三堆中的任意两堆,就可以实现异或值为0了.
比如14=8+4+2=(4*2+2*2+1*2),然后将4,2,1分别放入任意的两堆,有 C23C23C23=33 C 3 2 ∗ C 3 2 ∗ C 3 2 = 3 3 种放法,
但是其中像这种一堆都没有放数的情况应排除掉(共有3种)

①  4  1  2
②  0  0  0
③  4  1  2

同时,由于堆之间组合是没有顺序的,所以最终的结果应除以 A33 A 3 3 .
即最终结果为 3num36 3 n u m − 3 6 (num为n的二进制中含有1的个数).

代码实现

#include<bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);\
cin.tie(0);\
cout.tie(0);
typedef long long ll;
const int mod = 1e9+7;
#define INF 0x3f3f3f3f
const int maxn = 57;
int main()
{
    IO;
    int T;
    cin>>T;
    int n;
    while(T--)
    {
        cin>>n;
        if(n%2==1) cout<<"0"<<endl;
        else
        {
            int num=__builtin_popcount(n);
            ll ans=(pow(3.0,num)-3)/6;
            cout<<ans<<endl;
        }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值