Left Fortune law XOR and advanced classes 4_3 0 array is divided up to

【topic】

XOR array concepts and definitions:

All numbers in the array of exclusive OR up, the resulting array is called exclusive or, and,

Such as arrays {3,2,1} and the exclusive OR is 1 ^ 2 ^ 3 = 0

Given an array arr, arr you can put any into many sub-arrays incompatible, your goal is to:

He points out the sub-arrays, sub-arrays, and the exclusive OR of the most 0.

Please return to: sub-array points out, the XOR and an array of sub-zero most is how much?

【answer】

XOR operation properties:

Commutative and associative and 0 ^ m = m

DP, under the assumption that the number of array subscript is the last i, and there is an optimal array is divided, so that the maximum number of subarrays,

So i have two situations,

First, the division section i where XOR to zero;

Second, where the dividing section i, the exclusive OR is not 0.

For the first case dp [i] = dp [i - 1], and

For the second case, the interval is assumed that i is the optimal dividing [K, i], i is continuously or different is 0 to sum, a maximum of claim subscript k - 1, such that 0 to k - 1 iso or also for the sum on the line

[Code]

  

 1 #pragma once
 2 #include <iostream>
 3 #include <map>
 4 #include <vector>
 5 
 6 using namespace std;
 7 
 8 int XORSumArray(vector<int>v)
 9 {
10     int res = 0;
11     int Xor = 0;//异或和
12     vector<int>dp(v.size(), 0);
13     map<int, int>m;//key is the exclusive-or result, value appears represents the subscript 
14      m [ 0 ] = - . 1 ; // first the position and the exclusive OR is 0 -1 
15      for ( int I = 0 ; I <v.size (); + + I)
 16      {
 . 17          Xor ^ = [I] V;
 18 is          IF ! (m.find (Xor) = m.end ()) // exists 
. 19              DP [I] = m [Xor] == - . 1 ? . 1 : (DP [m [Xor]] + . 1 );
 20 is          IF (I> 0 )
 21 is              DP [I] DP = [I - . 1 ]> DP [I] DP [I -?1] : dp[i];
22         m[Xor] = i;
23         res = res > dp[i] ? res : dp[i];
24     }
25     return res;    
26 }
27 
28 void Test()
29 {
30     vector<int>v;
31     v = {1,2,3,1,2,3,1,2,3};
32     cout << XORSumArray(v) << endl;
33     v = {1,2,3,4,5,6,7,8,9,10};
34     cout << XORSumArray(v) << endl;
35     v = { 1,2,3,4,5,6,7,8,9,10,11 };
36     cout << XORSumArray(v) << endl;
37 }

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11070389.html