1189 - Sum of Factorials
| Time Limit: 0.5 second(s) | Memory Limit: 32 MB |
Given an integer n, you have to find whether it can be expressed as summation of factorials. For given n, you have to report a solution such that
n = x1! + x2! + ... + xn! (xi < xj for all i < j)
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n ≤ 1018).
Output
For each case, print the case number and the solution in summation of factorial form. If there is no solution then print'impossible'. There can be multiple solutions, any valid one will do. See the samples for exact formatting.
Sample Input | Output for Sample Input |
| 4 7 7 9 11 | Case 1: 1!+3! Case 2: 0!+3! Case 3: 1!+2!+3! Case 4: impossible |
Note
Be careful about the output format; you may get wrong answer for wrong output format.
题意:N如果可以表示成某几个数的阶乘则找出这几个数,不能的话输出impossible,不能有x相同的的数;
#include<cstdio>
#include<cstring>
typedef long long LL;
LL a[33],ord[33],cnt=0;
bool vis[30];//一夜没睡状态不好 错误百出循环条件 数组名称
bool solve(LL N)
{
LL i=0;
if(N==0) return true;
for(i=19;i>=0;--i)
{
if(N>=a[i]&&!vis[i]) {
break;
}
}
if(i==-1) return false;//<=N的都选完了 N还不为0
ord[++cnt]=i;
vis[i]=true;
if(solve(N-a[i])) return true;
return false;
}
int main()
{
LL i,T,N,Kase=0;
a[0]=1; for(i=1;i<=20;++i) a[i]=a[i-1]*i;
scanf("%lld",&T);
while(T--)
{
memset(vis,false,sizeof(vis));
scanf("%lld",&N); cnt=0;
printf("Case %lld: ",++Kase);
if(solve(N)) {
for(i=cnt;i>=1;--i)
{
if(i<cnt) printf("+");
printf("%lld!",ord[i]);
}
printf("\n");
}
else {
printf("impossible\n");
}
}
return 0;
}

本文探讨了如何解决一个整数是否能表示为若干个不同阶乘数之和的问题,并提供了一种有效的贪心算法解决方案。通过对输入整数进行递归拆解,找到构成该整数的所有阶乘数。


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



