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!>= 0!+1!+2!+3!+……+(n-1)!
20! = 2.4329020081766 * 10 18
思路:贪心,题目n最大范围是10^18,根据阶乘枚举到20 的阶乘就好,对于每个数n。从20至0 进行遍历,当n>=!时,记入数组s[k],
最后如果n=0,说明可以写为阶乘的和,否侧不能
代码:
#include <iostream>
#include <cstdio>
using namespace std;
#define LL long long
int main()
{
int t,kcase=1;
LL a[30];
a[0]=1;
for(int i=1;i<=21;i++){
a[i]=a[i-1]*i;
}
scanf("%d",&t);
while(t--)
{
LL n;int s[30];
scanf("%lld",&n);
int k=0;
for(int i=20;i>=0;i--)
{
if(n>=a[i])
{
s[k++]=i;
n-=a[i];
}
}
printf("Case %d: ",kcase++);
if(n!=0)
printf("impossible\n");
else
{
for(int i=k-1;i>0;i--)
{
printf("%d!+",s[i]);
}
printf("%d!\n",s[0]);
}
}
return 0;
}