Light Oj- 1189 - Sum of Factorials

题目内容: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; }

转载于:https://www.cnblogs.com/allanzheng/p/3228914.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值