HDU 5339 Untitled 解题报告
一、原题
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
二、题目大意:
每组数据包含n个除数,一个被除数a,现统计利用n个除数将a整除的最少次数,每个数字只能使用一次,顺序不要求。
三、思路:
贪心+状态压缩
贪心:参照样例我们可以发现,要实现除法次数最少,必须按照除数从大到小排列的顺序进行除法,否则余数过小,较大的除数实质不会被用到。
状态压缩:因n小于20,所以数据范围在1<<20即2^20内,可用int存,每位表示该除数是否使用,模拟全部状态,if((i>>j)&1)表示从右数第j位是否为1.
四、实现:
/*********************************
日期:2015-08-04
作者:matrix68
题号: HDU 5339
总结:状态压缩
Tricks:
**********************************/
#include <cstdio>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <cmath>
#define MP(a, b) make_pair(a, b)
#define PB push_back
#define Lowbit(x) ((x) & (-x))
#define Rep(i,n) for(int i=0;i<n;i++)
#define mem(arr,val) memset((arr),(val),(sizeof (arr)))
#define LL long long
const double PI = acos(-0);
const int MAXN = 10000 + 10;
const int MOD = 1000007;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
using namespace std;
int b[MAXN];
int main()
{
// freopen("in.txt","r",stdin);
int T;
int n,a;
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);
reverse(b,b+n);
int ans=n+10;
for(int i=0;i<(1<<n);i++)
{
int tmp=a;
int cnt=0;
for(int j=0;j<n;j++)
{
if((i>>j)&1)
{
tmp%=b[j];
cnt++;
}
}
if(tmp==0)
{
if(ans>cnt)
ans=cnt;
}
}
if(ans==n+10)
cout<<-1<<endl;
else
cout<<ans<<endl;
}
return 0;
}