HDU 5339 Untitled 状态压缩 BC round49 A

本文介绍了解决HDU5339问题的方法,采用贪心算法结合状态压缩技术,通过排序和逆序处理输入数据,遍历所有可能的状态以找出最小的除法操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HDU 5339 Untitled 解题报告

一、原题

Problem Description
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,现统计利用n个除数将a整除的最少次数,每个数字只能使用一次,顺序不要求。

 

三、思路:

贪心+状态压缩

贪心:参照样例我们可以发现,要实现除法次数最少,必须按照除数从大到小排列的顺序进行除法,否则余数过小,较大的除数实质不会被用到。

状态压缩:因n小于20,所以数据范围在1<<20即2^20内,可用int存,每位表示该除数是否使用,模拟全部状态,if((i>>j)&1)表示从右数第j位是否为1.

 

四、实现:


/*********************************
   日期:2015-08-04
   作者:matrix68
   题号: HDU 5339
   总结:状态压缩
   Tricks:
**********************************/
#include <cstdio>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <cmath>
#define MP(a, b) make_pair(a, b)
#define PB push_back
#define Lowbit(x) ((x) & (-x))
#define Rep(i,n) for(int i=0;i<n;i++)
#define mem(arr,val) memset((arr),(val),(sizeof (arr)))
#define LL long long
const double PI = acos(-0);
const int MAXN = 10000 + 10;
const int MOD = 1000007;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
using namespace std;
int b[MAXN];
int main()
{
//      freopen("in.txt","r",stdin);
    int T;
    int n,a;
    scanf("%d",&T);
    while(T--)
    {
         scanf("%d %d",&n,&a);
         for(int i=0;i<n;i++)
            scanf("%d",&b[i]);
         sort(b,b+n);
         reverse(b,b+n);

         int ans=n+10;
         for(int i=0;i<(1<<n);i++)
         {
            int tmp=a;
            int cnt=0;
            for(int j=0;j<n;j++)
            {
               if((i>>j)&1)
               {
                  tmp%=b[j];
                  cnt++;
               }
            }
            if(tmp==0)
            {
               if(ans>cnt)
                  ans=cnt;
            }
         }
         if(ans==n+10)
            cout<<-1<<endl;
         else
            cout<<ans<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值