Educational Codeforces Round 134 (Rated for Div. 2) DMaximum AND(位运算)

101 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第26天,点击查看活动详情
本文已参与「新人创作礼」活动,一 起开启掘金创作之路

题目

You are given two arrays aa and bb, consisting of nn integers each. Let's define a function f(a,b)f(a, b) as follows: let's define an array cc of size nn, where ci=aibic_i = a_i \oplus b_i (\oplus denotes bitwise XOR); the value of the function is c1&c2&&cnc_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n (i.e. bitwise AND of the entire array cc). Find the maximum value of the function f(a,b)f(a, b) if you can reorder the array bb in an arbitrary way (leaving the initial order is also an option).

中文大意

给你两个数组a和b,分别由n个整数组成。 让我们定义一个函数f(a,b)如下。 让我们定义一个大小为n的数组c,其中ci=ai⊕bi(⊕表示位XOR)。 该函数的值为c1&c2&⋯&cn(即整个数组c的位和)。 如果你能以任意的方式对数组b进行重新排序,找出函数f(a,b)的最大值(保留初始顺序也是一种选择)。

解法

我们发现本题是和位运算有关的那我们先来了解下位运算,&都为1才为1,^运算不同即为1.
应为要我们去求最大值所以我们肯定想让高位为1最好所以我们就从高位往低位去枚举看能否让高位为1 。因为最后的运算是^运算需要都不同所以我们想到了反码(因为反码肯定是和原码每一位都不一样的. 我们检测这一位能否变成1就是用&去处理看能否形成n个01配对如果可以就将这位置为1

Code

int a[N],b[N];
void solve()
{
   int n; cin >> n;
   rep(i,n) cin >> a[i-1];
   rep(i,n) cin >> b[i-1];
   int res = 0;
   for(int i = 30; i >= 0; i--) {
      vector<int>av(n),bv(n);
      for(int j = 0; j < n; j++) {
             av[j] = (a[j] & (res | (1 << i)));
             bv[j] = (~b[j] & (res | (1 << i)));
      }
      sort(all(av));
      sort(all(bv));
      if(av == bv) res |= 1 << i;
   }
   cout << res << endl;
}