LightOJ 1189 - Sum of Factorials(贪心)

Description

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


                                                                                          

比赛的时候以为 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值