Skip to content

Commit 580bfec

Browse files
Add Tutorial For LOJ-1234 Harmonic Number (en) (#456)
* Added Tutorial LOJ-1234 (en) * Added Tutorial * Update en.md Changed the solution approach * Update en.md
1 parent d7d5f33 commit 580bfec

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

1234/en.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# LOJ 1234 - Harmonic Number
2+
3+
## Solution
4+
We won't be able to iterate from 1 to n for each test-case independently, since it will not fit the time limit. What we can do is iterate once from `n=1` to `1e8` (max) and compute `H(n)` for each of them using `H(n) = H(n-1) + 1/n`. Whenever we come across a `n` that is queried in the input, we will save the value for output. After the iteration has been completed, we will output all the queries together.
5+
6+
### Complexity
7+
- Time Complexity: `O(MAX(N))`.
8+
- Memory Complexity: `O(T)`.
9+
10+
## C++ Code
11+
12+
```cpp
13+
#include <bits/stdc++.h>
14+
15+
using namespace std;
16+
17+
18+
int main() {
19+
20+
// For fast I/O
21+
ios_base::sync_with_stdio(false);
22+
cin.tie(nullptr);
23+
24+
const int MAXN = 1e8;
25+
26+
int t;
27+
cin >> t;
28+
29+
// 1-based indexing
30+
vector <pair <int, int>> N(t+1);
31+
for(int i = 1; i <= t; ++i) {
32+
cin >> N[i].first;
33+
// Saving corresponding index of the test case
34+
N[i].second = i;
35+
}
36+
sort(N.begin(), N.end());
37+
38+
vector <double> ans(t+1);
39+
double now = 0;
40+
int idx = 1;
41+
for(int i = 1; i <= MAXN; ++i) {
42+
now += 1.0 / i;
43+
// Could be duplicates, that's why using 'while' loop
44+
while (idx < (int)N.size() && N[idx].first == i) {
45+
ans[N[idx++].second] = now;
46+
}
47+
}
48+
49+
for(int ts = 1; ts <= t; ++ts) {
50+
cout << fixed << setprecision(10) << "Case " << ts << ": " << ans[ts] << '\n';
51+
}
52+
53+
return 0;
54+
}
55+
```

0 commit comments

Comments
 (0)