Nim (nim博弈+前缀异或和+思维)

Nim is a mathematical game of strategy in which two players take turns removing objects from distinct heaps. The game ends when one of the players is unable to remove object in his/her turn. This player will then lose. On each turn, a player must remove at least one object, and may remove any number of objects provided they all come from the same heap. Here is another version of Nim game. There are N piles of stones on the table. Alice first chooses some CONSECUTIVE piles of stones to play the Nim game with Tom. Also, Alice will make the first move. Alice wants to know how many ways of choosing can make her win the game if both players play optimally.

You are given a sequence a[0],a[1], ... a[N-1] of positive integers to indicate the number of stones in each pile. The sequence a[0]...a[N-1] of length N is generated by the following code:

 

int g = S; 

for (int i=0; i<N; i++) { 

    a[i] = g;

    if( a[i] == 0 ) { a[i] = g = W; }

    if( g%2 == 0 ) { g = (g/2); }

    else           { g = (g/2) ^ W; }

}

Input

There are multiple test cases. The first line of input is an integer T(T ≤ 100) indicates the number of test cases. Then T test cases follow. Each test case is represented by a line containing 3 integers NS and W, separated by spaces. (0 < N ≤ 105, 0 < S, W ≤ 109)

Output

For each test case, output the number of ways to win the game.

Sample Input

2
3 1 1
3 2 1

Sample Output

4
5

题意:通过他给的代码,跑出 n个数a[i]。 然后取任意多个连续的数,让他们 异或操作。 计算有多少种取法,使操作后结果为0.

思路:把前i个a的异或操作结果放在 sum[i]中, 那么a[i]到a[j]的异或结果就是 sum[i-1]^sum[j]。  

nim博弈若异或和不为零,则先手必胜。

取连续的数一共有n*(n+1)/2种,我们再把异或和为零的去掉就是结果了,那怎么处理呢?

若某连续区间[i,j]异或和为零,则sum[i-1]与sum[j]相等,设该值为k,则前面k出现了多少次,那么就有多少种不合题意。

注意,在遍历sum[i]之前,先mp[0]=1;  想想为什么?

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<map>
#include<vector>
#include<set>
#include<list>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
const int N=1e5+10;
ll T,n,s,w,a[N],ans;
int sum[N];
map<int,int> mp;
int main(){
	scanf("%lld",&T);
	while(T--){
		scanf("%lld%lld%lld",&n,&s,&w);
		mp.clear();
		int g = s; 
		int len = 0, s=-1;
        for (int i=0; i<n; i++) {
            a[i] = g; 
			if( a[i] == 0 ) { a[i] = g = w; }
         	if( g%2 == 0 ) { g = (g/2); }
         	else           { g = (g/2) ^ w; }
         	
			 
        } 
    	ll t=0;
    	ans=(ll)n*(n+1)/2;
    	mp[0]=1;
    	for(int i=0;i<n;i++){
    		t=t^a[i];
    		sum[i]=t;
    		mp[t]++;
    		ans-=(mp[t]-1);
		}
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42936517/article/details/88431725
Nim