【LightOJ】1189 - Sum of Factorials(思维)

来源:互联网 发布:省市地区数据库 编辑:程序博客网 时间:2024/04/30 14:40

点击打开题目

1189 - Sum of Factorials
   PDF (English)StatisticsForum
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





没有看到 “大众” 们的代码,不懂他们写的什么意思。

我当时看到了一个规律:后面一个数的阶乘总是大于等于前面的数的阶乘之和。

那么从最后往前走,如果给出的数大于了这个数的阶乘的2倍,那么肯定不成立。如果小于这个数的阶乘,那么继续往前扫,否则就选中这个数,然后减去它的阶乘,一直到这个数减为0.


代码如下:

#include <cstdio>#include <cstring>#include <cmath>#include <queue>#include <vector>#include <stack>#include <algorithm>using namespace std;#define INF 0x3f3f3f3f#define CLR(a,b) memset(a,b,sizeof(a))#define LL long long#define PI acos(-1.0)LL fac[25];bool flag;LL n;stack<int> s;int main(){int u;int Case = 1;fac[0] = 1;LL sum = 1;for (int i = 1 ; i <= 19 ; i++)fac[i] = fac[i-1] * i , sum += fac[i];scanf ("%d",&u);while (u--){scanf ("%lld",&n);printf ("Case %d: ",Case++);if (n > sum){puts("impossible");continue;}while (!s.empty())s.pop();flag = false;for (int i = 19 ; i >= 0 ; i--){if (n < fac[i])continue;else if (n == fac[i]){s.push(i);flag = true;break;}else if (n > 2*fac[i])break;else{s.push(i);n -= fac[i];}}if (flag){while (s.size() != 1){printf ("%d!+",s.top());s.pop();}printf ("%d!\n",s.top());s.pop();}elseputs("impossible");}return 0;}


0 0
原创粉丝点击