zoj2591 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
算法分析:这个题的最终转换为:在 a[n] 中找连续的 a[i]^a[i+1]^……^a[j] > 0 的个数;
用 s[i]=a[1]^a[2]^……^a[i] ; 则 a[i]^a[i+1]^……^a[j]=s[i]^s[j];
用总的个数 减去 不符合要求的个数 等于 答案;
总的个数 : n + n*(n-1)/2 = n*(n+1)/2;
不符合要求的 : 如果 s[i]=0 或者 s[i]==s[j] 就是不符合要求的 把 s[] 排序,就ok了。
View Code
 1 #include<iostream>
2 #include<algorithm>
3 #define N 100010
4 #include<cstdio>
5
6 using namespace std;
7
8 int a[N],s[N];
9
10 void init(int n,int s,int w)
11 {
12 int g = s;
13 bool falg=false;
14 for (int i=0; i<n; i++)
15 {
16 a[i] = g;
17 if( a[i] == 0 )
18 {
19 a[i] = g = w;
20 }
21 if( g%2 == 0 )
22 {
23 g = (g/2);
24 }
25 else
26 {
27 g = (g/2) ^ w;
28 }
29 }
30 }
31
32 long long work(long long n)
33 {
34 int i,k;
35 long long ans=n*(n+1)/2;//这里必须也用long long 否则会 爆空间的
36 s[0]=a[0];
37 for(i=1;i<n;i++)
38 s[i]=a[i]^s[i-1];
39 sort(s,s+n);
40 for(i=0;i<n;i++)
41 {
42 k=1;
43 int j=i;
44 while(s[j]==0)
45 {
46 j++;
47 ans--;
48 }
49 while(s[i]==s[i+1])
50 {
51 i++;k++;
52 }
53 ans=ans-k*(k-1)/2;
54 }
55 return ans;
56 }
57
58 int main()
59 {
60 long long n;
61 int s,w,test,i;
62 cin>>test;
63 while(test--)
64 {
65 cin>>n>>s>>w;
66 init(n,s,w);
67 cout<<work(n)<<endl;
68 }
69 return 0;
70 }

posted @ 2012-04-09 00:28  mtry  阅读(393)  评论(0编辑  收藏  举报