BestCoder #49 Untitled HDU 5339
题目: http://acm.hdu.edu.cn/showproblem.php?
本题採用深搜, 数据量小,先做排序处理(降序), 然后深搜的时候,进行剪枝,比K大的数就不是必需往后搜索,直接剪掉。
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int INF = 200;
int arr[20+5] = {};
void dfs(int t, int n, int k, int &ans)
{
if (k==0)
{
ans = min(ans, t);
return;
}
if (t < n)
{
if (k%arr[t] == 0)
{
ans = min(ans, t+1);
}
else if (k > arr[t]) // 要做剪枝处理, 大于k 就不是必需往后处理了
{
dfs(t+1, n, k%arr[t], ans);
dfs(t+1, n, k, ans);
}
}
}
inline bool cmp(const int &a, const int &b)
{
return a > b;
}
int main(void)
{
//freopen("in.txt", "r", stdin);
int t = 0;
cin>>t;
while(t--)
{
int n, k;
cin>>n>>k;
int zero = 0; // 假设输入数据含有 k 的因子,那么结果肯定是 1
int v = 0;
int j = 0;
for(int i=0; i<n; ++i)
{
scanf("%d", &v);
if (k%v == 0)
zero = 1;
if (v < k)
arr[j++] = v;
}
if (zero == 1)
{
printf("1\n");
continue;
}
sort(arr, arr+j, cmp); // order by DESC
//printf("%d\n", arr[0]);
int ans = INF;
dfs(0, j, k, ans);
printf("%d\n", ans==INF ? -1: ans);
}
return 0;
}
浙公网安备 33010602011771号