Friday, 5 February 2021

Sum of Factorials Lightoj 1189

 In this problem we will pre calculate all the factorial values upto 20(because the constraint). Then greedily we will just check can we take the value of factorial of any number.

#include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define mp make_pair
#define f0(n) for(int i=0;i<n;i++)
#define ms(x) memset(x,0,sizeof(x))
#define ins insert
#define IOS ios::sync_with_stdio(false);
using namespace std;
int main()
{
    IOS
    int t;
    cin>>t;
    ll fact[21];
    fact[0] = 1;
    for(int i=1;i<=20;i++)
    {
        fact[i] = fact[i-1]*i;
        //cout << fact[i] << endl;
    }
    for(int tc=1;tc<=t;tc++)
    {
        ll n;
        cin>>n;
        vector<int>vec;
        for(int i=20;i>=0;i--)
        {
            if(fact[i]<=n)
            {
                n-=fact[i];
                vec.pb(i);
            }
            if(n==0) break;
        }
        sort(vec.begin(),vec.end());
        cout << "Case "<< tc << ": ";
        if(n!=0) {cout <<"impossible\n";continue;}
        for(int i=0;i<vec.size();i++)
        {
            if(i>0 && i<vec.size())
                cout << "+";
            cout << vec[i] << "!";
        }
        cout << endl;
    }
    return 0;
}

No comments:

Post a Comment

If you have any doubts, let me know through comments

Monkey Banana Problem lightoj 1004

  In this problem we will check which adjacent cell will benefits the monkey best. For this, we will check all possible solution of this pro...