ZOJ - 3591 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 N, S 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

题目大意就是先由给定的程序生成 a 数组,让后选择 a 中连续的序列,进行尼姆游戏,判断先手获胜次数。
普通的尼姆游戏只要所有数的异或值不等于 0 ,那么先手必赢。这个题是要选出来一段序列判断,显然直接枚举是不现实的,那么需要考虑一下什么时候异或为0,显然当两个数相同的时候,即 sum [ i - 1 ] 和 sum [ j ] 相同的时候,i ~ j 的异或值为0,这个也比较好证,在最后附上吧。那么可以考虑维护一下前缀异或值,当某两个前缀的异或值相等的时候,那么选择他们之间的区间的时候,先手必败。而我们需要求出先手必赢的数量,那么可以考虑转换一下,由于知道所有区间的数量为 n * ( n + 1 ) / 2 ,只需要求出不符合要求的数量,减去即可。
实际写代码的时候,用map存一下当前值出现的数量即可,只是用到了前缀和思想,不需要开一个前缀和数组。

sum [ j ] = sum [ i - 1 ] ^ sum [ i ~ j ]
sum [ j ] ^ sum [ i - 1 ] = sum [ i - 1 ] ^ sum [ i - 1 ] ^ sun [ i ~ j ]
sum [ j ] ^ sum [ i - 1 ] = sum [ i ~ j ]

#include<cstdio>
#include<iostream>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值