Lightoj1189——Sum of Factorials(阶乘的和+贪心)

来源:互联网 发布:淘宝客服招聘靠谱吗 编辑:程序博客网 时间:2024/06/05 10:09

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
Output for Sample Input

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.

原来这种题直接从大到小贪心就行了。。。

#include <iostream>#include <cstring>#include <string>#include <vector>#include <queue>#include <cstdio>#include <set>#include <cmath>#include <algorithm>#define INF 0x3f3f3f3f#define MAXN 2005#define Mod 10001using namespace std;long long num[23];void Init(){    num[0]=num[1]=(long long)1;    for(int i=2; i<21; ++i)        num[i]=num[i-1]*i;}int main(){    Init();    int t,cnt=1;    scanf("%d",&t);    while(t--)    {        long long n;        vector<int> ans;        scanf("%lld",&n);        for(int i=20; i>=0; --i)        {            if(n>=num[i])            {                n-=num[i];                ans.push_back(i);            }        }        printf("Case %d: ",cnt++);        if(n!=0)        {            printf("impossible\n");            continue;        }        sort(ans.begin(),ans.end());        for(int i=0; i<ans.size(); ++i)        {            if(i!=0)                printf("+");            printf("%d!",ans[i]);        }        printf("\n");    }    return 0;}
0 0
原创粉丝点击