【Trie】The XOR Largest Pair

[Link] title

https://loj.ac/problem/10050

[Title] Italy

Given number n, wherein to remove the two numbers, the maximum allowed value XOR.

【answer】

The classic 01 trie problem.

01 trie first need to build it.

For each string are then run again. If the current bit different node exists, go out there to run, or run down.

All in the code.

 

[Code]

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int N = 1e5+10;
 5 const int M = 3e6+10;
 6 int son[M][2];
 7 int a[N],n,idx;
 8 void Insert(int x){
 9     int p = 0 ;
10     for(int i=31;~i;i--){
11         int t = x >> i & 1 ;
12         if( !son[p][t] )
13             son[p][t] = ++idx;
14         p = son[p][t] ;
15     }
16 }
17 int Query(int x){
18     int p = 0 ;
19     int res = 0 ;
20     for(int i=31;~i;i--){
21         int t = x >> i & 1 ;
22         if( son[p][t^1] ){
23             res += 1<<i ;
24             p = son[p][t^1] ;
25         }else{
26             p = son[p][t] ;
27         }
28     }
29     return res ;
30 }
31 int main()
32 {
33     scanf("%d",&n);
34     for(int i=1;i<=n;i++)
35         scanf("%d",&a[i]),Insert(a[i]);
36     int res = 0 ;
37     for(int i=1;i<=n;i++)
38         res = max( Query(a[i]) , res );
39     printf("%d\n",res);
40     return 0 ;
41 }
01 trie

 

Guess you like

Origin www.cnblogs.com/Osea/p/11361488.html