div2-664 C. Boboniu and Bit Operations

C. Boboniu and Bit Operations
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Boboniu likes bit operations. He wants to play a game with you.

Boboniu gives you two sequences of non-negative integers 𝑎1,𝑎2,…,𝑎𝑛 and 𝑏1,𝑏2,…,𝑏𝑚.

For each 𝑖 (1≤𝑖≤𝑛), you're asked to choose a 𝑗 (1≤𝑗≤𝑚) and let 𝑐𝑖=𝑎𝑖&𝑏𝑗, where & denotes the bitwise AND operation. Note that you can pick the same 𝑗 for different 𝑖's.

Find the minimum possible 𝑐1|𝑐2|…|𝑐𝑛, where | denotes the bitwise OR operation.

Input
The first line contains two integers 𝑛 and 𝑚 (1≤𝑛,𝑚≤200).

The next line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (0≤𝑎𝑖<29).

The next line contains 𝑚 integers 𝑏1,𝑏2,…,𝑏𝑚 (0≤𝑏𝑖<29).

Output
Print one integer: the minimum possible 𝑐1|𝑐2|…|𝑐𝑛.

Examples
inputCopy
4 2
2 6 4 0
2 4
outputCopy
2
inputCopy
7 6
1 9 1 9 8 1 0
1 1 4 5 1 4
outputCopy
0
inputCopy
8 5
179 261 432 162 82 43 10 38
379 357 202 184 197
outputCopy
147
Note
For the first example, we have 𝑐1=𝑎1&𝑏2=0, 𝑐2=𝑎2&𝑏1=2, 𝑐3=𝑎3&𝑏1=0, 𝑐4=𝑎4&𝑏1=0.Thus 𝑐1|𝑐2|𝑐3|𝑐4=2, and this is the minimal answer we can get.

/*
 * 题意: 给你两个数组a长度为n(1~200), b长度为m(1~200),定义数组c为c[i] = a[i] & b[j],一个b[h]可以和多个a[i]配对,然后让你求c[0] | c[1] ... | c[n - 1]的最小值
 *  数组a,b的元素范围(0~2^9-1)
 *
 * 解决: 之前老是想着贪心,但是贪心是没法满足最优解的。换个思路,数组元素最大是2^9 - 1,刚好是二进制(1111 1111),所以最后的c[0] | c[1] ... | c[n - 1]的范围
 *  也只能是[0~2^9-1],所以只需要从0到2^9-1遍历即可,找到一个解就是最后结果
 */

#include <bits/stdc++.h>

using namespace std;

int n, m;
int a[234], b[234];

bool check(int x) {
  bool ok;
  for (int i = 0; i < n; i++) {
    ok = false;
    for (int j = 0; j < m; j++) {
      if (((a[i] & b[j]) | x) == x) {
        ok = true;
        break;
      }
    }
    if (!ok) return false;
  }
  return true;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);

  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> a[i];
  for (int i = 0; i < m; i++) cin >> b[i];

  for (int res = 0; res < 512; res++) {
    if (check(res) == true) {
      cout << res << "\n";
      break;
    }
  }

  return 0;
}
posted @ 2020-08-13 10:56  勿忘初心0924  阅读(359)  评论(2编辑  收藏  举报