DESCRIPTION
Coco just learned a math operation call mod.Now,there is an integer a and n integers b1,…,bn. After selecting some numbers from b1,…,bn in any order, say c1,…,cr, Coco want to make sure that amodc1modc2mod…modcr=0\ (i.e., a will become the remainder divided by ci each time, and at the end, Coco want a to become 0). Please determine the minimum value of r. If the goal cannot be achieved, print −1 instead.
INPUT
The first line contains one integer
T(T≤5), which represents the number of testcases. For each testcase, there are two lines:1. The first line contains two integers
n and
a\ (
1≤n≤20,1≤a≤106).2. The second line contains
n integers
b1,…,bn\ (
∀1≤i≤n,1≤bi≤106).
OUTPUT
Print
T answers in
T lines.
SAMPLE INPUT
22 92 72 96 7
SAMPLE OUTPUT
2-1
SOLUTION
对于一组可能的答案
c
,如果先对一个觉小的
ci
取模,再对一个较大的
cj
取模,那么这个较大的
cj
肯定是没有用的。因此最终的答案序列中的
c
肯定是不增的。那么就枚举选哪些数字,并从大到小取模看看结果是否是
0
就可以了。时间复杂度
O(2n)
.
代码
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAXN = 1000010;
int a[MAXN],vis[MAXN],N,ans;
void dfs(int x,int cut)
{
if(x == 0)
{
ans = cut;
return;
}
for(int i = 0 ; i < N && a[i] <= x; i++)
{
if(!vis[x % a[i]])
vis[x % a[i]] = 1,dfs(x % a[i],cut + 1);
if(ans != -1) return;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int A;
scanf("%d %d",&N,&A);
for(int i =0; i <N; i++) scanf("%d",&a[i]);
memset(vis,0,sizeof(vis));
ans = -1;
sort(a,a+N);
dfs(A,0);
printf("%d\n",ans);
}
return 0;
}