C -- Coco
Time Limit:1s Memory Limit:64MByte
Submissions:262Solved:125
DESCRIPTION
Coco just learned a math operation call mod.Now,there is an integer aa and nn integers b1,…,bnb1,…,bn. After selecting some numbers from b1,…,bnb1,…,bn in any order, say c1,…,crc1,…,cr, Coco want to make sure that amodc1modc2mod…modcr=0amodc1modc2mod…modcr=0\ (i.e., aa will become the remainder divided by cici each time, and at the end, Coco want aa to become 00). Please determine the minimum value of rr. If the goal cannot be achieved, print −1−1 instead.
INPUT
The first line contains one integer
T(T≤5)T(T≤5), which represents the number of testcases. For each testcase, there are two lines:1. The first line contains two integers
nn and
aa\ (
1≤n≤20,1≤a≤1061≤n≤20,1≤a≤106).2. The second line contains
nn integers
b1,…,bnb1,…,bn\ (
∀1≤i≤n,1≤bi≤106∀1≤i≤n,1≤bi≤106).
OUTPUT
Print
TT answers in
TT lines.
SAMPLE INPUT
22 92 72 96 7
SAMPLE OUTPUT
2-1
题意:给一个数k和其他n个数,问能否从n个数中任选几个数使k模这几个数之后结果为0。若能则输出最少选的数字个数,不能输出-1。
思路:一开始还思考错了,还是wonderful的思路清晰,直接从大到小排序,然后比k大的数直接跳过,比k小的数每次递归模,中间只要模到结果为0就结束,并更新最小值。
#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
#include<math.h>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int ans=10000000;
int num[30];
bool run(int a,int s,int e,int step){
if(a==0){
if(step<ans)
ans=step;
return true;
}
int i;
for(i=s;i<e;i++){
if(num[i]<=a)
break;
}
if(i==e)
return false;
for(;i<e;i++){
return run(a%num[i],i+1,e,++step);
}
}
int main(){
int t;
int n,a;
cin>>t;
while(t--){
ans=10000000;
cin>>n>>a;
for(int i=0;i<n;i++){
cin>>num[i];
}
sort(num,num+n,cmp);
if(run(a,0,n,0))
cout<<ans<<endl;
else
cout<<-1<<endl;
}
return 0;
}