DFS(dfs)

时间:2024-01-09 16:28:56

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=2212

DFS

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6322    Accepted Submission(s): 3898

Problem Description
A DFS(digital factorial sum) number is found by summing the factorial of every digit of a positive integer.

For example ,consider the positive integer 145 = 1!+4!+5!, so it's a DFS number.

Now you should find out all the DFS numbers in the range of int( [1, 2147483647] ).

There
is no input for this problem. Output all the DFS numbers in increasing
order. The first 2 lines of the output are shown below.

Input
no input
Output
Output all the DFS number in increasing order.
Sample Output
1
2
......
Author
zjt
题解:开始想到10位数,枚举每一位数字肯定会超时,O(10的10次方) 根据枚举的情况,1!+4!+5!和5!+4!+1!是一样的,所以可以从大到小按照顺序枚举出所有情况,即可,这样下一个位置枚举的时候就不可以出现比最后小的元素了,这里注意0的阶乘是1,而且为了避免第一位出现0 的情况,从最后一位向前枚举,最后的输出结果只有4个数,所以可以之间打表输出这4个数即可
 #include<cstdio>
#include<algorithm>
using namespace std;
//#define N 8776444321ll//要在后面加ll 这样不会超int
#define ll long long
const ll N = ;
ll ans[];
int c ;
int f[],g[];
int a[];
int ck(ll sum)
{
for(int i = ; i < ; i++) f[i] = ,g[i] = ;
ll v = sum;
ll tm = ;
while(v)
{
tm+=a[v%];
f[v%]++;
v/=;
}
v = tm;
while(tm)
{
g[tm%]++;
tm/=;
}
for(int i = ;i < ; i++) if( f[i]!=g[i] ) return -;
return v;
}
void dfs(int cur, ll sum)
{
ll res = ck(sum);
if(sum>N) return ;
if(res!=-) ans[c++] = res;
for(int i = cur ; i >= ; i-- )
{
if(sum==&&i==) continue;
dfs(i,sum*+i);
}
}
int main()
{
a[] = a[] = ;
for(int i = ; i < ; i++)
a[i] = a[i-]*i;
c = ;
dfs(,);
sort(ans,ans+c);
for(int i = ; i < c ; i++)
printf("%lld\n",ans[i]);
return ;
}

其实得到输出结果后可以直接打表:

 #include <cstdio>
using namespace std;
int main()
{
puts("");
puts("");
puts("");
puts("");
return ;
}