ZOJ_3591_Nim_机智的前缀和
来源:互联网 发布:淘宝店铺评分能看到吗 编辑:程序博客网 时间:2024/05/01 04:58
累得一笔。
题意:
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. ThenT test cases follow. Each test case is represented by a line containing 3 integersN, 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
- ZOJ_3591_Nim_机智的前缀和
- 游戏《机智的小鸟》
- 机智的交换函数
- 机智的末位无空格
- 机智的偶数求和
- zufe-机智的zhourist
- 机智的简单计算器
- 妙语连珠-机智的回答
- mybatis的缓存机智
- 机智的AmyZhi
- 字符串的前缀和后缀
- 特殊函数的前缀和
- 你这个机智的家伙
- ZOJ 3475(机智的暴力)
- acm 2045 无尽的机智
- 机智的图灵机器人
- 前缀和
- 前缀和
- Xcode自动注释插件
- 10000 pcs free gift of chinese top grade brown film faced plywood
- 排列组合的小程序
- Integrity constraint violation: 1052 Column 'id' in order clause is ambiguou
- 查找相邻元素是否相等
- ZOJ_3591_Nim_机智的前缀和
- iOS storeboard 页面传值 教程
- 数据结构_二叉树基础
- Qt利用代码实现流水灯的效果
- Nginx 优化指南 绝对详细
- 输入迭代器源码ostream_iterator
- 黑马程序员_日记52_泛型限定初级使用
- ZigBee多节点无线物联自组网设计
- mac下生成ssh