Untitled
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 751 Accepted Submission(s): 403
Problem Description
There is an integer
a
and
n
integers
b1,…,bn
. After selecting some numbers from
b1,…,bn
in any order, say
c1,…,cr
, we want to make sure that
a mod c1 mod c2 mod… mod cr=0
(i.e.,
a
will become the remainder divided by
ci
each time, and at the end, we 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≤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 ).
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
2 2 9 2 7 2 9 6 7
Sample Output
2 -1
Source
可以用动态规划或者dfs来解决。
使用dfs最好先排序一下,动态规划则不用。
动态规划: dp[i]表示以i为结尾的满足条件的最小序列长度,dp[i]=min(dp[i],dp[i%b[j]]+1),j>=1 && j<=n
开始可以设置dp全为无穷大,dp[0]=0.
#include<map>
#include<vector>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<stack>
#include<queue>
#include<set>
#define inf 0x3f3f3f3f
#define mem(a,x) memset(a,x,sizeof(a))
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
inline int in()
{
int res=0;char c;
while((c=getchar())<'0' || c>'9');
while(c>='0' && c<='9')res=res*10+c-'0',c=getchar();
return res;
}
int b[22];
int dp[1000010];//dp[i]以i为结尾的最短序列
int main()
{
int T=in();
while(T--)
{
int n=in(),a=in();
mem(dp,inf);
for(int i=1;i<=n;i++)b[i]=in();
dp[0]=0;
for(int i=1;i<=a;i++)
{
for(int j=1;j<=n;j++)
{
dp[i]=min(dp[i],dp[i%b[j]]+1);
}
}
// for(int i=0;i<=a;i++)cout<<dp[i]<<" ";
// cout<<endl;
printf("%d\n",dp[a]==inf?-1:dp[a]);
}
return 0;
}
dfs版本,对于每个数选或者不选。
#include<map>
#include<vector>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<stack>
#include<queue>
#include<set>
#define inf 0x3f3f3f3f
#define mem(a,x) memset(a,x,sizeof(a))
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
inline int in()
{
int res=0;char c;
while((c=getchar())<'0' || c>'9');
while(c>='0' && c<='9')res=res*10+c-'0',c=getchar();
return res;
}
int ans;
int b[22];
void dfs(int n,int x,int cnt)
{
if(x==0)
{
ans=min(ans,cnt);
return;
}
if(n<0)return;
dfs(n-1,x%b[n],cnt+1);
dfs(n-1,x,cnt);
}
int main()
{
for(int T=in();T;T--)
{
int n=in(),a=in();
for(int i=0;i<n;i++)b[i]=in();
sort(b,b+n);
ans=inf;
dfs(n-1,a,0);
printf("%d\n",ans==inf?-1:ans);
}
return 0;
}