Left Fortune law 7_1 seeking the most advanced classes and sub-array XOR

【topic】

Given an array, the array Praying largest and XOR.

And an array of exclusive-or array, or all of the number of different results together.

【answer】

I must be up to the end of the array or the maximum and the exclusive

Violent solution is O (N3), each number is the cycle of violence again

XOR properties:

e1 ^ e2 = e3

e1 = e2 ^ e3;

e2 = e3 ^ e1;

Prefix tree:

The 0 ~ i and the exclusive OR calculated, converted into binary data

Then a binary tree of binary data

Then how to find the maximum and XOR?

In addition to the first hope is to 0, because the first negative 1

Then try to walk behind the number 1 of this road, then the road is the biggest and XOR

The main difficulty is to use the number of shift positions in the respective bit binary extracted

 【Code】

  

 1 #pragma once
 2 #include <iostream>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 class TreeNode
 8 {
 9 
10 public:
11     struct Node
12     {
13         int val;
14         vector<Node*>nexts;
15         Node(int a) :val(a), nexts({ nullptr,nullptr }) {}
16     };
17 
18     void add(int num)
19     {
20         Node* cur = head;
21         for (int i = 31; i >= 0; --i)
22         {
23             int k = ((num >> i) & 1);//取出每一位数字
24             cur->nexts[k] = cur->nexts[k] == nullptr ? new Node(-1) : cur->nexts[k];
25             cur = cur->nexts[k];
26         }
27     }
28 
29     int maxXor(int num)
30      {
 31 is          the Node * = CUR head;
 32          int S = 0 ;
 33 is          for ( int I = 31 is ; I> = 0 ; - I)
 34 is          {
 35              int K = (NUM >> I) & . 1 ; // from a highest one extracted data 
36              int B = I == 31 is K: (K ^? . 1 );
 37 [              B = cur> nextS [B] nullptr a = B: (B ^!? . 1 );
 38 is              S | = (K ^ B) << I;
 39             cur = cur->nexts[b];
40         }
41         return s;
42     }
43 public:
44     Node* head = new Node(-1);
45 };
46 
47 
48 int getMaxXOR(vector<int>num)
49 {
50     if (num.size() == 0)
51         return 0;
52     int xors = 0;
53     int res = INT_MIN;
54     TreeNode numTree;
55     numTree.add(0);
56     for (auto a : num)
57     {
58         xors ^= a;
59         res = res > numTree.maxXor(xors) ? res : numTree.maxXor(xors);
60         numTree.add(xors);
61     }
62     return res;        
63 }
64 
65 
66 void Test()
67 {
68     vector<int>v;
69     v = { 1,2,3,4,5 };
70     cout << getMaxXOR(v) << endl;
71 }

 

Guess you like

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