ZOJ_3591_Nim_机智的前缀和

累得一笔。


题意:

Nim游戏标配,各堆石头的石头数依次为a[0], a[1], ... , a[n-1],他们的数值由下面的程序生成:

 
 
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; }
}
其中S, W为题目参数,问:从这些石头堆里选出连续的一堆石头玩Nim游戏,有多少种选法在双方都机智的情况下先手胜。



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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值