lightoj-1189-Sum of Factorials【思维】
原创
©著作权归作者所有:来自51CTO博客作者Somethingwill的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目链接:点击打开链接
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.
题解:注意一下 Xi < Xj 而且 i < j ;其实想来数据是先进后出嘛,那不就是栈嘛
#include<cstdio>
#include<algorithm>
#include<cstring>
#define LL long long
using namespace std;
LL n;
LL fac[21];
int ans[50];
void get()
{
fac[0]=1;
for(int i=1;i<=20;i++)
{
fac[i]=fac[i-1]*i;
}
}
int main()
{
int t,text=0;
get();
scanf("%d",&t);
while(t--)
{
scanf("%lld",&n);
int num=0;
for(int i=20;i>=0;i--)
{
if(n>=fac[i])
{
n-=fac[i];
ans[num++]=i;
}
}
printf("Case %d: ",++text);
if(n) puts("impossible");
else
{
for(int i=num-1;i>=0;i--)
{
printf(i==0?"%d!":"%d!+",ans[i]);
}
puts("");
}
}
return 0;
}
栈模拟
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
typedef long long LL;
LL n,fac[21];
void get()
{
fac[0]=1;
for(int i=1;i<21;i++)
fac[i]=fac[i-1]*i;
}
stack<int> fafe;
int main()
{
int t,text=0;
scanf("%d",&t);
get();
while(t--)
{
scanf("%lld",&n);
while(!fafe.empty()) fafe.pop();
for(int i=20;i>=0;i--)
{
if(n>=fac[i])
{
n-=fac[i];
fafe.push(i);
}
}
printf("Case %d: ",++text);
bool flag=0;
if(n) puts("impossible");
else
{
/*while(!fafe.empty())
{
if(flag) putchar('+');
printf("%d!",fafe.top());
fafe.pop();
flag=1;
}*/
while(fafe.size())
{
printf(fafe.size()==1?"%d!":"%d!+",fafe.top());
fafe.pop();
}
puts("");
}
}
return 0;
}