LightOJ 1189 - Sum of Factorials(贪心)

来源:互联网 发布:网络水军有多少 编辑:程序博客网 时间:2024/04/29 16:45

Description

Given an integer n, you have to find whether it can be expressed as summation of factorials. For givenn, 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


                                                                                          

比赛的时候以为 10的18次方会爆long long, 敲了个高精度模板,就不知道要怎么写了。傻啊>.<

long long : 10的18次方,int 10的4次方。

打阶乘表,以每个数为基点,从后往前加。

CODE:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;typedef long long ll;ll num[20];int ans[20];void cal(){    num[0] = 1;    num[1] = 1;    for(int i = 2; i < 21; ++i) {        num[i] = num[i - 1] * i;    }}int main(){//freopen("in", "r", stdin);    int T;    scanf("%d", &T);    cal();    printf("%lld\n", num[20]);    int cas = 0;    while(T--) {        cas++;        printf("Case %d: ", cas);        ll n, s;        scanf("%lld", &n);        int as;        for(int i = 0; i < 21; ++i) {            if(num[i] > n) {                printf("impossible\n");                break;            } //使用这样的判断,要计算到20,否则当n大于19!但是小于20!时则没有答案输出。            as = 0;            s = 0;            ll nn = n;            for(int j = i; j >= 0; --j) {                if(nn - num[j] >= 0) {                    nn -= num[j];                    ans[as++] =j;                    if(nn == 0) {                        printf("%d!", ans[as-1]);                        for(int k = as - 2; k >= 0; --k) {                            printf("+%d!", ans[k]);                        }                        printf("\n");                        break;                    }                }            }            if(nn == 0) break;        }    }    return 0;}


0 0
原创粉丝点击