BestCoder #49 Untitled HDU 5339,
BestCoder #49 Untitled HDU 5339
題目: http://acm.hdu.edu.cn/showproblem.php?pid=5339
本題採用深搜, 資料量小,先做排序處理(降序), 然後深搜的時候,進行剪枝,比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;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。 http://blog.csdn.net/core__code