Perfect Security(01字典树)

题目链接

题意:给你两个序列A,B,求一个序列C c[i]=a[i]^b[i]你可以重新排列B序列,且要答案字典序最小。

思路:对B序列建树,然后在A序列查找,为了找到数尽可能小,那么贪心的时候就是看01树上的点和有没有和当前位一样的有的话就选他,异或后对答案没影响,没有的话就只能加上当前位异或值(1<<i),还要删除字典树的节点,我们用sum[i]记录一想当前节点还有几个子节点可以走,当子节点减为0时则不能走。

//#pragma GCC optimize(2)
#include<bits/stdc++.h>
 
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=1e7+5;

int gcd(int a,int b)
{
    
    
    return b==0?a:gcd(b,a%b);
}
 
ll lcm(ll a,ll b)
{
    
    
    return a*(b/gcd(a,b));
}
 
template <class T>
void read(T &x)
{
    
    
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    
    
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
         write(x / 10);
    putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
    
    
    ll res=1%p;
    while(b)
    {
    
    
        if(b&1)
            res=res*a%p;
        a=1ll*a*a%p;
        b>>=1;
    }
    return res;
}
int trie[N][2],root, tot;
int sum[N];
int a[N];

void Insert(int  x)
{
    
    
    
    root = 0;
    for (int i = 30; i >=0; i--)
    {
    
    
        int id =x>>i&1;//转为2进制;
        if (!trie[root][id]){
    
       
            trie[root][id] = ++tot;
        }
        root = trie[root][id];
        sum[root]++;
    }
    //sum[root]=x;
}
int Search(int x)
{
    
    
    root = 0;
    int res=0;
    for (int i = 30; i>=0; i--)
    {
    
    
        int id =x>>i&1;
        if(trie[root][id]&&sum[trie[root][id]])
        {
    
    
            root=trie[root][id];
        }
        else{
    
    
            root=trie[root][id^1];
            res|=1<<i;

        }
        sum[root]--;
            
    }
    return res;
}

int main()
{
    
    

  



      int n,m;
      scanf("%d",&n);
      for(int i=1;i<=n;i++)scanf("%d",&a[i]);
      for(int i=1;i<=n;i++){
    
    
          int x;
          scanf("%d",&x);
          Insert(x);
      }
      
      int tm=0;
      for(int i=1;i<=n;i++)
      {
    
    
          printf("%d ",Search(a[i]));

      }
     
      
       
      

    return 0;

}


猜你喜欢

转载自blog.csdn.net/qq_43619680/article/details/109522591