hdu 5339 Untitled
题目大意:给出n个数字的序列,和一个数a,在n中有m个数b1,...,bm使得__a %b1%b2%...%bm = 0,求最小的m。
解题思路:回溯。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
const int N = 50;
const int INF = 50;
typedef long long ll;
int n, a, cnt;
int num[N];
int vis[N], ans;
void DFS(int x, int dis) {
if (dis >= ans) return;
if (x == 0) {
if (ans > dis) ans = dis;
return;
}
for (int i = 0; i < cnt; i++) {
if (num[i] > x) break;
if (!vis[i]) {
vis[i] = 1;
DFS(x % num[i], dis + 1);
vis[i] = 0;
}
}
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
ans = INF;
scanf("%d %d", &n, &a);
int temp, flag = 0;
cnt = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &temp);
if (temp == a || temp == 1) {
flag = 1;
break;
} else if (temp < a) {
num[cnt++] = temp;
}
}
if (flag) {
printf("1\n");
continue;
}
sort(num, num + cnt);
DFS(a, 0);
if (ans == INF) printf("-1\n");
else printf("%d\n", ans);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许也可以转载,不过要注明出处哦。
时间: 2024-10-12 08:56:22