Skip to content

Commit 5f5a2c2

Browse files
committed
updated
1 parent dcf0101 commit 5f5a2c2

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

1189-sum_of_factorials.cpp

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
#define MAX 100100
4+
5+
using namespace std;
6+
7+
ll arr[22];
8+
ll facto[22];
9+
vector <pair <ll, ll> > v;
10+
11+
void fact()
12+
{
13+
facto[0] = 1;
14+
15+
for (int i = 1; i < 21; i++)
16+
facto[i] = i * facto[i - 1];
17+
}
18+
19+
ll yes ;
20+
ll indx;
21+
22+
void recursive(ll num, ll pos)
23+
{
24+
// cout << num << endl;
25+
if (num == 0 )
26+
{
27+
yes = 1;
28+
return;
29+
}
30+
31+
if (pos == -1)
32+
return;
33+
34+
if (num >= facto[pos]) {
35+
arr[indx] = pos;
36+
indx++;
37+
recursive(num - facto[pos], pos - 1 );
38+
return;
39+
}
40+
41+
recursive(num, pos - 1);
42+
}
43+
44+
45+
46+
int main()
47+
{
48+
#ifndef ONLINE_JUDGE
49+
freopen("/home/sameer/Documents/sameer/input.sam", "r", stdin);
50+
#endif
51+
ios_base::sync_with_stdio(false);
52+
ll i, j, k, n, m, t, cont, a, b;
53+
cin >> t;
54+
ll cases = t;
55+
fact();
56+
57+
while (t--) {
58+
cin >> n ;
59+
yes = 0;
60+
indx = 0;
61+
memset(arr, 0, sizeof arr);
62+
recursive(n, 20);
63+
cout << "Case " << cases - t << ": " ;
64+
65+
if (yes == 1) {
66+
for (i = indx - 1; i > 0; i--)
67+
cout << arr[i] << "!+";
68+
69+
cout << arr[0] << "!\n";
70+
71+
} else {
72+
cout << "impossible\n";
73+
}
74+
}
75+
76+
return 0;
77+
}

README.md

+10
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,16 @@ and continue the loop ,till we find n as odd number.
470470
one by one.
471471

472472

473+
##Solution 1189 :
474+
475+
As the time limit is too low 0.5 sec,if we do bitmasking , it will
476+
be timeout .
477+
if we observe carefully ,
478+
fact[n] > fact[n-1] + fact[n-2] + ..... fact[1] + fact[0].
479+
which means , if , k > fact[n] , and if k is a valid solution , then
480+
k must contain fact[n] .
481+
so just we need a single recursive call instead of double call inside
482+
the recursive function.
473483

474484
##Solution 1233 :
475485

0 commit comments

Comments
 (0)