Description
给出一个数字a和一个数组b,现在让你从b数组中选取最少的元素,使得a依次模完这些元素后为0,输出最少元素的数量,如果不存在合理方案则输出-1
Input
第一行为用例组数T,每组用例第一行为两个整数n和a,第二行有n个整数表示b数组
Output
对于每组用例,输出最少的元素数量,如果不存在合理方案则输出-1
Sample Input
2
2 9
2 7
2 9
6 7
Sample Output
2
-1
Solution
因为b数组元素数量不超过20,所以可以2^n枚举所有情况不断更新满足条件的最小元素数量即可,因为每次肯定模较大数才可能将a模成0,所以先将b数组降序排
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<string>
#include<set>
#include<map>
using namespace std;
int cmp(int x,int y)//降序排
{
return x>y;
}
int main()
{
int t,a,n,b[22],c[22];
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&a);
for(int i=0;i<n;i++)
scanf("%d",&b[i]);
sort(b,b+n,cmp);//排序
int ans=22,flag=0;
for(int i=0;i<(1<<n);i++)//2^n枚举所有情况
{
int k=0;
for(int j=0;j<n;j++)//找到此情况使用的元素
if(i&(1<<j))
c[k++]=b[j];
int temp=a;
for(int j=0;j<k;j++)
temp%=c[j];
if(!temp)//满足条件
{
flag=1;
ans=min(ans,k);//更新最小元素数量
}
}
if(flag)//有解
printf("%d\n",ans);
else//无解
printf("-1\n");
}
return 0;
}