zoj3591 Nim-----位运算 博弈

来源:互联网 发布:扫描ip地址软件 编辑:程序博客网 时间:2024/05/16 19:06
Nim

Time Limit: 3 Seconds      Memory Limit: 65536 KB

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 areN 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. 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.

Sample Input

23 1 13 2 1

Sample Output

45
题意:就是给你n个数,然后从这n个数中选择连续的几个数做NIM游戏,问取胜的有多少种选择方法。
看到这题,很没思路。
首先n个数,选择连续的几个数的总的方法有n*(n+1)/2种。
然后我们用nim[]这个数组把从1……i这i个数的异或值存到nim[i]中。
nim[i]==nim[j]则表示,i+1,i+2……j的异或值为0,即选择这几个连续的数是必败态的。
然后,如果nim[i]==0,则表示从1……i这几个数是必败态。
把这些必败态减去,则是取胜的种数了。
#include<iostream>#include<cstdlib>#include<stdio.h>#include<algorithm>using namespace std;int N,S,W;int a[100010];int nim[100010];void init(){    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;    }}int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d%d",&N,&S,&W);        init();        nim[0]=a[0];        for(int i=1;i<N;i++)        nim[i]=nim[i-1]^a[i];        long long  ans=(long long)N*(N+1)/2;//没有(long long) 会WA        sort(nim,nim+N);        int l=1;        for(int i=1;i<N;i++)        {            if(nim[i]==nim[i-1]) l++;            else            {                if(nim[i-1]==0) ans-=l;                ans-=(long long)l*(l-1)/2;//c(l,2)                l=1;            }        }        ans-=(long long)l*(l-1)/2;        printf("%lld\n",ans);    }}

原创粉丝点击