zoukankan      html  css  js  c++  java
  • HDU 5676 ztr loves lucky numbers【DFS】

    题目链接;

    http://acm.hdu.edu.cn/showproblem.php?pid=5676

    题意:

    由4和7组成的且4和7出现次数相同的数称为幸运数字,给定n,求不大于n的最大幸运数字。

    分析:

    可以对于每个数都按位dfs找一发。一旦发现当前位无法满足就回溯,直到找到满足条件的最小的。
    也可以先按位dfs把所有结果都找出来存起来,然后对于每个询问直接二分即可。注意边界时会爆long long,注意处理。

    代码:

    #include<cstdio>
    #include<cstring>
    char s[50];
    int len;
    bool found;
    int four, seven;
    void write(int len)
    {
        for(int i = 0; i < len/2; i++) printf("4");
        for(int i = 0; i < len/2; i++) printf("7");
        printf("
    ");
    }
    void dfs(long long ans, long long res, int lens)
    {
        if(lens == len && !found){
            found = true;
            printf("%I64d
    ", ans);
        }
        if(found) return;
        res = res * 10 + s[lens] - '0';
        if(res <= ans * 10 + 4 && four < len / 2){
            four++;
            dfs(ans * 10 + 4, res, lens + 1);
            four--;
            res /= 10;
        }
        if(found) return;
        if(res <= ans * 10 + 7 && seven < len / 2){
            seven++;
            dfs(ans * 10 + 7, res, lens + 1);
            seven--;
            res /= 10;
        }
    }
    int main()
    {
        int T;scanf("%d", &T);
        while(T--){
            scanf("%s", s);
            len = strlen(s);
            if(len & 1) write(len + 1);
            else{
                four = seven = 0;
                found = false;
                dfs(0, 0, 0);
                if(!found) write(len + 2);
            }
        }
        return 0;
    }
    
    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    long long a[100000 + 5];
    int tot = 0;
    void dfs(int four, int seven, long long ans)
    {
        if(four == seven)  a[tot++] = ans;
        if(four < 9) dfs(four + 1, seven, ans * 10 + 4);
        if(seven < 9) dfs(four, seven + 1, ans * 10 + 7);
    }
    int main (void)
    {
        dfs(0, 0, 0);
        int t;cin>>t;
        sort(a, a + tot);
        while(t--){
            long long n;cin>>n;
            if(!n) {cout<<47<<endl;continue;}
            int res = lower_bound(a, a + tot, n) - a;
            if(res == tot) cout<<"44444444447777777777"<<endl;
            else cout<<a[res]<<endl;
        }
        return 0;
    }
    
  • 相关阅读:
    手机怎么知道5G基站的存在?(小区搜索和SSB简介)
    Python中*args,**kwargs两个参数的作用?
    python之jupyter的安装
    国内安装python库速度慢的解决办法
    MOSFET:金属-氧化物半导体场效应晶体管
    C# 小知识点汇总
    ajax和form和七个中间件
    BBS功能分析
    MVC和MTV
    自关联和auth模块
  • 原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758641.html
Copyright © 2011-2022 走看看