【codeforces 96B】Lucky Numbers (easy) DFS

Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.

One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.

Input

The only line contains a positive integer n (1 ≤ n ≤ 109). This number doesn't have leading zeroes.

Output

Output the least super lucky number that is more than or equal to n.

Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.

Examples
Input
Copy
4500
Output
4747
Input
Copy
47
Output
47

题目大意:给你一个数,输出一个大于等于它的、只由4和7两个数字构成,并且4和7的数量相等的数字。

由题意知:

1、首先得数的数位肯定是偶数。

2、而且就算原数字的数位是偶数,得数的数位也不一定是偶数。因为比如7788,你就需要一个444777才能比它大。

3、还有个问题就是输入的数字才10的9次方,也就是说最多9位,那么就可以根据它的大小直接确定最终输出的数位是多少。比如大于74小于等于7744的数,输出的就是4位数。大于7744小于等于777444的,输出的就是6位数。

然后直接dfs一发,所有情况来一遍,找个最小的就行了。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
__int64 num;int m;__int64 ans;
int b[100];
void dfs(int sum,int sum4,int sum7)
{
    if(sum==m)
    {
        __int64 c=1;__int64 num1=0;
        for(int i=m-1;i>=0;i--)
        {
            num1+=(b[i]*c);
            c*=10;
        }
        if(num1>=num&&num1<ans)ans=num1;
        return ;
    }
    if(sum4)
    {
        b[sum]=4;
        dfs(sum+1,sum4-1,sum7);
    }
    if(sum7)
    {
        b[sum]=7;
        dfs(sum+1,sum4,sum7-1);
    }
}
int main()
{
    char a[100];
    while(~scanf("%s",a))
    {
        int n=strlen(a);
        num=0;__int64 c=1;
        for(int i=n-1;i>=0;i--)
        {
            num+=(c*(a[i]-'0'));
            c*=10;
        }
        m=0;
        if(num<=74)m=2;
        else if(num>74&&num<=7744)m=4;
        else if(num>7744&&num<=777444)m=6;
        else if(num>777444&&num<=77774444)m=8;
        else if(num>77774444)m=10;
        int sum7=m/2;int sum4=m/2;
        ans=7777744444;
        dfs(0,sum4,sum7);
        printf("%I64d\n",ans);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值