题目:http://acm.hdu.edu.cn/showproblem.php?pid=5339
大意:在所有的给定的一定数目的数字中选择最少的数字让他们满足:a%b1%b2%……%bn=0。输出最小的n.
暴力枚举和DFS的本质都是一样的:
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int INF=1e6+10;
int b[21];
int n,a,minm;
bool cmp(int a,int b){
return a>b;
}
void dfs(int number,int dex,int sum){
if(number==0){
minm=min(minm,sum);
return ;
}
if(dex==n-1)return ;
dfs(number%b[dex+1],dex+1,sum+1);
dfs(number,dex+1,sum);
}
int main()
{
//freopen("cin.txt","r",stdin);
int t;
cin>>t;
while(t--){
memset(b,0,sizeof(b));
scanf("%d%d",&n,&a);
for(int i=0;i<n;i++){
scanf("%d",&b[i]);
}
sort(b,b+n,cmp);
minm=INF;
dfs(a,-1,0);
if(minm>n)minm=-1;
printf("%d\n",minm);
}
return 0;
}
递归很神奇的有木有,哈哈~~
来看二进制枚举:
#include <iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int INF=1e6+10;
int b[21];
int n,a;
bool cmp(int a,int b){
return a>b;
}
int main()
{
//freopen("cin.txt","r",stdin);
int t;
cin>>t;
while(t--){
scanf("%d%d",&n,&a);
int minm=INF;
for(int i=0;i<n;i++){
scanf("%d",&b[i]);
}
sort(b,b+n,cmp);
int dex=0;
for(int i=0;i<n;i++){
if(b[i]>a)continue;
dex=i;
break;
}
for(int i=0;i<(1<<(n-dex));i++){
int temp=a,res=0;
for(int j=0;j<n-dex;j++){
if((1<<j)&i){
res++;
temp=temp%b[j+dex];
if(temp==0){ minm=min(minm,res); break; }
}
}
}
printf("%d\n",minm>20?-1:minm);
}
return 0;
}