累得一笔。
题意:
Nim游戏标配,各堆石头的石头数依次为a[0], a[1], ... , a[n-1],他们的数值由下面的程序生成:
其中S, W为题目参数,问:从这些石头堆里选出连续的一堆石头玩Nim游戏,有多少种选法在双方都机智的情况下先手胜。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.
Nim游戏当游戏中所有石头堆数量异或和为0时先手输,否则胜,这题要求a数组中有多少段异或和不为0,异或和为0等价于相等。先求前缀异或和sum数组,因为异或一个数两次等于没异或,因此可以想加法前缀和一样方便地使用。问题转化为有多少不相等的i, j使得sum[i]==sum[j]。只需给sum数组排个序,之后O(n)扫一遍,统计每个相同值的数量cnt用C(cnt, 2)求就行了。最后答案用C(n+1, 2)减去这个数即可。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int sum[100005];
int n,s,w;
int a[100005];
int main()
{
int T;
scanf("%d",&T);
while (T--)
{
scanf("%d%d%d",&n,&s,&w);
sum[0]=0;
int g=s;
for (int i=1;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;
sum[i]=a[i]^sum[i-1];
}
sort(sum,sum+n+1);
int i=0,j=1;
long long ans=0;
while (i<=n)
{
int cnt=1;
while (sum[j]==sum[i]&&j<=n) {++j;++cnt;}
ans+=cnt*(cnt-1)/2;
i=j;j=i+1;
}
ans=((long long)n+1)*n/2-ans;
printf("%lld\n",ans);
}
return 0;
}