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
SOLUTION
这道题第一次用的DP,完全背包的思路写的,结果超内存,改成滚动数组又超时。后来想了想,觉得枚举往下搜索一下应该也行,结果BFS一下就过了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
#define mem(p,k) memset(p,k,sizeof(p))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define inf 0x5fffffff
#define LL long long
using namespace std;
int b[25];
struct SD {
int c,m;
}f,p;
queue<struct SD> a;
bool cmp(int a,int b){
return a>b;
}
int main(){
int t;
cin>>t;
while(t--){
int n,k,j,i,cur=0;
cin>>n>>k;
for(int i=0;i<n;i++)scanf("%d",b+i);
sort(b,b+n,cmp);
while(!a.empty())a.pop();
f.m=k;f.c=0;//cout<<f.m;
a.push(f);
while(!a.empty()){
f=a.front();
a.pop();
for(i=0;i<n;i++){//cout<<f.m<<endl;
if(f.m==b[i]){
cur=f.c+1;
break;
}
if(b[i]<f.m){//因为余数下降,被除数必定小于除数,所以往下枚举就行了
p.m=f.m%b[i];
p.c=f.c+1;
a.push(p);
}
}
if(cur)break;
}
if(cur)cout<<cur<<endl;
else cout<<-1<<endl;
}
return 0;
}