Help Dexter

Help Dexter

题目链接
题目描述:给定一个p,q求出最大和最小的十进制p位数,使得该数s只含1或2并且s|2^q。
题目描述
You know Dexter, right? He is a very talented young scientist. He has a huge lab hidden inside his building. He made all possible security arrangement to keep his naughty sister Dee Dee away from his lab. But she always finds a way into the lab. One day Dee Dee came to the lab and started her usual work, messing up Dexter’s lab! Dexter was working on a very important project, so he begged to her and said, “Please!!! Not today. I will do anything for you, but please leave this lab today!!!” Dee Dee was waiting for this chance, she said, “Ok, you do my homework I won’t disturb you today.” What can Dexter do? He agreed. Dee Dee said, “My teacher told me to write down 17 numbers. First one single digit number, second one two digit number, …, nth one n digit number. They will consist of only digit 1 and 2 and the nth number should be divisible by 2n.” Dexter thought, “I have very little time to finish the project. I can’t waste my time for this silly problem, I have bigger problem to think!” So, he sent the modified version of this problem to you. Hurry up, Dee Dee is waiting.
输入
Input starts with an integer T (≤ 300), denoting the number of test cases.
Each case starts with two integers: p q (1 ≤ p, q ≤ 17).
输出
For each case, print the case number first. Then you have to find two integers (smallest and largest) which have p digits and is divisible by 2q. The integers should contain only 1’s and 2’s. If no result is found, print “impossible”. If there is only one integer, then print that integer. Otherwise print both integers (first the smallest one then the largest one) separated by a single space.
样例输入
3
2 2
2 1
2 3
样例输出
Case 1: 12
Case 2: 12 22
Case 3: impossible

思路:DFS,组合出所有的可能数,并更新最大最小值,由于p<=17,时间复杂度O(2^17),不会导致超时。

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
ll max1;//动态记录最大值
ll min1;//动态记录最小值
int p,q;//p代表位数,q代表2进制数
ll ant;//存放2^p
int dfs(ll num,int ans)
{   if(ans>p) return 1;//位数大于位置
    if(num%ant==0&&ans==p)//更新最大最小值
    {    if(min1==-1) min1=num;
         else min1=min(min1,num);
         if(max1==-1) max1=num;
         else max1=max(max1,num);
         return 1;
    }
    else
    {
        for(int i=1;i<=2;i++) dfs(num*10+i,ans+1);//深度地柜查找
    }
    return 1;
}
int main()
{
    int T;
    scanf("%d",&T);
    for(int cnt=1;cnt<=T;cnt++)
    {   min1=-1;
        max1=-1;
        scanf("%lld%lld",&p,&q);
        ant=1;
        while(q--)
        {
            ant*=2;
        }
        dfs(0,0);
        printf("Case %d:",cnt);
        if(min1==-1) printf(" impossible\n");
        else if(min1==max1) printf(" %lld\n",min1);
        else printf(" %lld %lld\n",min1,max1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值