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;
}
原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758641.html