题目内容: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
4
7
7
9
11
Sample Output
Case 1: 1!+3!
Case 2: 0!+3!
Case 3: 1!+2!+3!
Case 4: impossible
一道简单的贪心加上一点点数学技巧,由题目的数据范围可以推测出只有0到20的阶乘,而且除了0与1的阶乘相同以外,任意一个数的阶乘都大于小于它的自然数的阶乘之和,所以我们可以很放心从大到小贪心选择一个数的阶乘正好是小于或等于所给的数据,然后从所要求的数减去,再一直配对下去,如果剩下为0,则输出,否则输出impossible。
代码如下:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long s[25]= {0};
int t[25]={0};
int source()
{s[0]=1;
long long mid=1,i=1;
for(int j=1; j<=20; j++)
{
mid=1;
for(i=1; i<=j; i++)
mid*=i;
s[j]=mid;
//cout<<s[j]<<endl;
}
return 0;
}
int main()
{
int n;
long long num;
scanf("%d",&n);
source();
for(int i=1; i<=n; i++)
{
memset(t,0,sizeof(t));
int j=0,ca=0;
scanf("%lld",&num);
long long mid1=num;
int tr=0;
while(mid1>=1&&!tr&&j<20)
{
for(int i=20; i>=0; i--)
{ if(s[i]==mid1&&t[i]==0)
{
mid1=0;
t[i]=1;
tr=1;
ca++;
break;
}
else if(s[i]<mid1&&t[i]==0)
{
mid1-=s[i];
t[i]=1;
ca++;
}
//cout<<s[i]<<' '<<mid1<<endl;
j++;}
}
int mid2=1;
printf("Case %d: ",i);
if(mid1!=0)
printf("impossible\n");
else
for(int c=0; c<=20; c++)
{
if(t[c]&&mid2<ca)
{
printf("%lld!+",c);
mid2++;
}
else if(t[c])
printf("%lld!\n",c);
}
}
return 0;
}