HDOJ-----5339---Untitled暴力枚举+剪枝

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 T5 , which represents the number of testcases.

For each testcase, there are two lines:

1. The first line contains two integers n and a ( 1n20,1a106 ).

2. The second line contains n integers b1,,bn ( 1in,1bi106 ).
 

Output
Print T answers in T lines.
 

Sample Input
  
  
2 2 9 2 7 2 9 6 7
 

Sample Output
  
  
2 -1

给出n个数,问能不能取出其中一些令a依次对这些数取模之后最终值为0,若有,输出所需最少的数,没有,输出-1

枚举n个数所有的可能组合结果

加上剪枝即可

注意是从大到小依次取模,从小到大的话只能取第一个,后边的无意义

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<set> 
#include<queue>
#include<vector>
#include<functional>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define CL(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
const int MOD = 1e9+7; 
int num[50];
int n, a, ans;
void solve(int cur, int c, int cnt){
    if(!c){//判断,取模之后为0,满足即可更新最小值,返回
        ans = min(ans, cnt);
        return ;
    }
    if(cnt >= ans) return ;//当前遍历的组合数已大于最小值,返回
    for(int i = cur; i < n; i++){
        if(num[i] <= c) solve(cur+1, c%num[i], cnt+1);//对大于自身的数取模还是本身,无意义,剪枝
    }//一开始把这个if判断放在下一层递归导致错误,必须在当前循环判断
}
bool cmp(int c, int d){
    return c > d;
}
int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        scanf("%d%d", &n, &a);
        for(int i = 0; i < n; i++) scanf("%d", &num[i]);
        sort(num, num+n, cmp);
        ans = INF;
        solve(0, a, 0);
        printf("%d\n", ans == INF ? -1 : ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值