http://acm.hdu.edu.cn/showproblem.php?pid=5676
#include <iostream>
#include <algorithm>
using namespace std;
#define M 100000000
__int64 table[M],k=0;
void dfs(int p4,int p7,__int64 s) //用dfs打表
{
if(p4+p7<=18&&p4<=9&&p7<=9)
{
if(p4==p7&&s!=0)
{
table[k++]=s; // 4,7个数相等时 保存
}
dfs(p4+1,p7,s*10+4); //加数字4
dfs(p4,p7+1,s*10+7); //加数字7
}
}
long fun(__int64 n)
{
long l=0,r=k,mid,pos;
while(l<r)
{
mid=(l+r)/2;
if(n>table[mid])
{
l=mid+1; //第一个比n大的一定在mid之后
pos=l;
}
else
{
r=mid;// 第一个比n大的一定在mid之前(可能是mid)
pos=r;
}
}
return pos;
}
int main()
{
__int64 n,pos;
long i,j,t;
dfs(0,0,0);
sort(table,table+k);
scanf("%d",&t);
while(t--)
{
scanf("%I64d",&n);
if(n>table[k-1]) //特判
{
for(i=1;i<=10;i++)
{
printf("4");
}
for(i=1;i<=10;i++)
{
printf("7");
}
printf("\n");
continue;
}
pos=fun(n); //二分找到第一个比n大的幸运数
printf("%I64d\n",table[pos]);
}
return 0;
}
本文介绍了一个使用深度优先搜索(DFS)生成所有由4和7组成的幸运数,并通过二分查找找到大于给定数值的第一个幸运数的算法实现。该算法首先通过DFS生成所有可能的幸运数并进行排序,然后针对每个输入数值,利用二分查找快速定位到第一个大于该数值的幸运数。

297

被折叠的 条评论
为什么被折叠?



