3566 Triple Nim

Triple Nim
Time Limit: 2000 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
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).
题意:利用nim博弈的性质,nim博弈所有局势异或不为0先手赢,为0后手赢;
此题Alice先手,Bob有所有的石子N,Bob把石子分成三个堆,想让自己赢,那么每一堆得石子数异或必须为0;

我第一次直接遍历,超时,,

正解:
假设有N个石子,转换为二进制,二进制中有k个1。转换为三个数;如果要是三个数异或为0那么转换三个数的二进制数每位上1的个数必须为偶数。每两个低位1相加得到一个高位的1,而所以每两个低位的1由高位的1分解而来。
SO,,当n为奇数,最低位为1且没有办法分解,所以输出0,
,当n为偶数,就有(3^k - 3)/6个,减去3是去掉一个为0的情况,除6是应为本题求得是排列。重复A33。。

输出,没用long long 结果wrong了,,测试中接近亿位时,int出错,改为long long OK

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
int fin(long long int x){
    long long ans = 0;
    while(x){
        if(x&1){
            ans++;
        }
        x>>=1;
    }
    return ans;
}
int main()
{
    int T;
    cin >> T;
    while(T--){
        long long int m;
        cin >> m;
        if(m&1) printf("0\n");
        else{
            long long int s = fin(m);
            //cout << s<<endl;
            cout <<(pow(3.0,s)-3)/6 << endl;
           // cout << (long long)(pow(3.0,s)-3)/6 << endl;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/hanyanwei123/article/details/80170462
Nim