题目链接:http://lightoj.com/volume_showproblem.php?problem=1189点击打开链接
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.
18<20! 所以只需要把0~19的阶乘打表 然后因为数太大 不能用数组储存0~sum(0!~19!)的每个数 因此需要逐个判断 另外还需要n!>=0!+1!+...(n-1)!的知识
从19开始判断 如果这个数大于该数阶乘两倍 就impossible 如果在一倍到两倍之间就减去 小于就往下找 依次往下判断 然后用book记录输出
另外吐槽这个网站。。用着很不舒服。。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include<algorithm>
#include <math.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <vector>
using namespace std;
long long int a[22];
long long int s=0;
void jc()
{
a[0]=1;
for(int i=1;i<=20;i++)
a[i]=a[i-1]*i;
for(int i=0;i<=20;i++)
{
s+=a[i];
}
}
int main()
{
jc();
int n=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
long long int nn=0;
int book[22];
int flag=1;
memset(book,0,sizeof(book));
scanf("%lld",&nn);
printf("Case %d: ",i);
if(nn>s||nn==0)
{
printf("impossible\n");
flag=0;
}
else
{
for(int i=19;i>=0;i--)
{
if(nn>(2*a[i]))
{
printf("impossible\n");
flag=0;
break;
}
else if(a[i]<=nn&&nn<=a[i]*2)
{
nn-=a[i];
book[i]=1;
}
else if(nn==0)
break;
}
if(flag)
{
for(int i=0;i<20;i++)
if(book[i])
{
printf("%d!",i);
for(int j=i+1;j<20;j++)
if(book[j])
{
printf("+%d!",j);
}
cout << endl;
break;
}
}
}
}
}