time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
There is an array with n elements a1, a2, …, an and the number x.
In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the bitwise and operation.
You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
Input
The first line contains integers n and x (2 ≤ n ≤ 100 000, 1 ≤ x ≤ 100 000), number of elements in the array and the number to and with.
The second line contains n integers ai (1 ≤ ai ≤ 100 000), the elements of the array.
Output
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
Examples
inputCopy
4 3
1 2 3 7
outputCopy
1
inputCopy
2 228
1 1
outputCopy
0
inputCopy
3 7
1 2 3
outputCopy
-1
Note
In the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.
In the second example the array already has two equal elements.
In the third example applying the operation won’t change the array at all, so it is impossible to make some pair of elements equal.
正确代码:
#include<bits/stdc++.h>
using namespace std;
long long a[100010] = {0}, b[100010] = {0},c[100010] = {0};
int main() {
long long i, j, f = 0, n, m, k;
cin >> n >> k;
for(i = 1; i <=n; i++) {
cin >> a[i];
if(b[a[i]] == 1) {
f = 1;
}
b[a[i]] = 1;
}
if(f == 1) {
cout << 0;
return 0;
}
f = 0;
for(i = 1; i <= n; i++) {
if(b[(a[i]&k)] == 1 && ((a[i]&k) != a[i])) {
cout << 1;
return 0;
}
}
for(i = 1; i <= n; i++) {
a[i] = (a[i] & k);
if(c[a[i]] == 1) {
cout << 2;
return 0;
}
c[a[i]]=1;
}
cout << -1;
}
错误代码:
不见了。。。。。
思维误区:
没有对所以情况进行深度讨论,没有找出进行判断的特征。
总结:
1.还是用面向过程的思维来写题目
2.在使用下标进行访问数据时要从1开始进行录入
3.有限长度进行快速判断是否有重复:
for(i = 1; i <=n; i++) {
cin >> a[i];
if(b[a[i]] == 1) {
f = 1;
}
b[a[i]] = 1;
}
不仅可以边输入边判断,还能在变化时快速找到:
for(i = 1; i <= n; i++) {
if(b[(a[i]&k)] == 1 && ((a[i]&k) != a[i])) {
cout << 1;
return 0;
}
}
4.分步进行判断条件:
1.首先判断0次的
2.然后判断1次的
3.再判断2次的(其中因为一次的已经出去可以省略一些判断条件)
4最后剩下没有的