zoj3591 Nim

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 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
题意,就是,给几个数,可以求出每堆石子数,要求有多少个连续段可以,有必胜的把握!如果,枚举,有n*(n+1)/2个,肯定超时!如果,是要求出段数的话,我们知道可以用n*(n-1)/2;我们反过来想,要求必胜,我们可以求要败的个数,再用总数相减就ok了,怎么求败的局面呢,我们用pri[i]表前i项的异或和,那么如果pri[i]==pri[j]那么i,j这之间的一段异或和一定是0,如果我们把所有的相等的找在一起,再一起求组合,不就可以得到线性的算法了么!
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
#define LL long long
#define M 100500
int a[M],pri[M];
int main()
{
    int tcase,n,s,w;
    scanf("%d",&tcase);
    while(tcase--){
        scanf("%d%d%d",&n,&s,&w);
        int g = s;
        LL ans=0;
        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;
            }
        }
        pri[0]=0;
        for(int i=1;i<=n;i++)
        pri[i]=pri[i-1]^a[i-1];
        sort(pri+1,pri+n+1);
        ans=((LL)(n+1))*((LL)n)/2;
        LL len=1;
        for(int i=2;i<=n;i++){
           if(pri[i]!=pri[i-1]){
               if(pri[i-1]==0)
               ans-=len;
               ans-=len*(len-1)/2;
               len=1;
            }
           else len++;
        }
        ans-=len*(len-1)/2;
        printf("%lld\n",ans);
    }
    return 0;
}


你可能感兴趣的:(zoj3591 Nim)