And(CF-1013B)
Problem Description
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
Input
4 3
1 2 3 7
Output
1
Input
2 228
1 1
Output
0
Input
3 7
1 2 3
Output
-1
題意:給出兩個數?n 與 x,以及長度為 n 的一個數組 a[n],現在問數組中是否有相同的元素,如果有輸出0,如果沒有則進行?a[i] & x 操作,然后與原數組相比,如果有相同的元素,就輸出1,如果還是沒有,就看是否存在一個數操作完后與這個數相等,如果存在就輸出2,否則,輸出-1?
思路:
讀題讀的螺旋升天。。??粗﹄y其實就是一個模擬水題。。。
先比較原數組,看是否有相同的元素,如果有直接輸出0
再進行?a[i] & x 操作,將操作后的數全部記錄下來,與原來的數組進行比較,看是否有相同的,如果有,就輸出1
如果還是沒有,就用這個數操作完之后的數在新的數組中尋找相同的數,如果能找到,就輸出2
如果以上三步操作后均沒有,就輸出-1
Source Program
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<set> #include<map> #include<stack> #include<ctime> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 200001 #define MOD 1e9+7 #define E 1e-6 #define LL long long using namespace std; int a[N]; int b[N]; int main() {int n,x;cin>>n>>x;for(int i=1;i<=n;i++)cin>>a[i];sort(a+1,a+n+1);for(int i=1;i<=n-1;i++)//原數組尋找相同元素{if(a[i]==a[i+1]){cout<<0<<endl;return 0;}}for(int i=1;i<=n;i++)//存儲新數組b[i]=a[i]&x;for(int i=1;i<=n;i++)//在新數組中尋找與原數組相同的元素{for(int j=1;j<=n;j++){if(b[i]==a[j]&&i!=j){cout<<1<<endl;return 0;}}}sort(b+1,b+n+1);for(int i=1;i<=n-1;i++)//在新數組尋找相同元素{if(b[i]==b[i+1]){cout<<2<<endl;return 0;}}cout<<-1<<endl;return 0; }?
總結
以上是生活随笔為你收集整理的And(CF-1013B)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛的旅行(信息学奥赛一本通-T1343)
- 下一篇: Brackets(POJ-2955)