Codeforces Round #500 (Div. 2)B.And(思考+利用set去重)

B. And

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard 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

input

Copy

4 3
1 2 3 7

output

Copy

1

input

Copy

2 228
1 1

output

Copy

0

input

Copy

3 7
1 2 3

output

Copy

-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.

题意就是,给出一个数x和n个数,问这n个数能否通过与x进行&操作出现两个相同的数,若能输出最短的变化次数

不难想到,他最多有这几种情况:

0次:n个数中原本就有相同的数

1次:一个数通过一次变化变成了另一个数

2次:有两个原本不同的数通过各一次变换变成了同一个数

无解:不论如何变换不会出现相同的数

不难发现,一个数最多进行一次&操作,再多次数也不会发生变化了。

因此我们决定将所有的数和变化了一次且数值发生变化的数都分别存入一个set和一个multiset,然后先比较原数的set和multiset的元素数量得出是否原来有相同的数,再遍历储存原数的set看是否有数和变化一次的数相等的数,再比较变化后的数的set和multiset的元素数量得出有无两个不同数通过变化变成同一个数的情况。如果都没有,则无法变化

代码:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>

using namespace std;

int main()
{
	multiset<int> s1,s2;
	set<int> s3,s4;
	int n,k;
	int flag=0;
	while(cin>>n>>k)
	{
		s1.clear();s2.clear();s3.clear();s4.clear();
		flag=0;
		int num;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&num);
			s1.insert(num);
			s3.insert(num);
			if((num&k)!=num)
			{
				s2.insert(num&k);
				s4.insert(num&k);
			}
		} 
		if(s1.size()!=s3.size())
		{
			cout<<'0'<<endl;
			continue;
		}
		for(auto it=s1.begin();it!=s1.end();it++)
		{
			if(s4.count(*it))
			{
				flag=1;
				cout<<'1'<<endl;
				break;
			}
		}
		if(flag) continue;
		if(s2.size()!=s4.size())
		{
			cout<<'2'<<endl;
			continue;
		}
		cout<<"-1"<<endl;
		
	}
	return 0;
}

其实最好还是用unique写,set会慢上不少

posted @ 2018-07-31 20:01  Fly_White  阅读(200)  评论(0编辑  收藏  举报