forked from codereport/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamic_Programming_03_Sam.cpp
More file actions
97 lines (73 loc) · 1.93 KB
/
Copy pathDynamic_Programming_03_Sam.cpp
File metadata and controls
97 lines (73 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// code_report Solution
// https://youtu.be/kXS66eP0T6s
// SOLUTION 1 - O(n^2)
#include <iostream>
#include <vector>
#include <string>
#include <numeric>
using namespace std;
const int MOD = 1000000007;
auto substrings (string s) {
auto ans = 0LL;
vector<long long> dp;
for (auto c : s) {
for (auto& e : dp) e *= 10, e += c - '0', e %= MOD;
dp.push_back (c - '0');
ans += accumulate (dp.begin (), dp.end (), 0LL) % MOD;
}
return ans % MOD;
}
int main () {
string n;
cin >> n;
cout << substrings (n) << endl;
}
// SOLUTION 2 - O(n) - less algorithms
#include <vector>
#include <iostream>
#include <string>
using namespace std;
const int MOD = 1000000007;
long substrings (string s) {
int n = s.size ();
vector<long> a (n), b (n); // a = weight, b = weight sum
a[0] = 1, b[0] = 1;
for (int i = 1; i < n; i++) {
a[i] = (10 * a[i - 1]) % MOD;
b[i] = (b[i - 1] + a[i]) % MOD;
}
long ans = 0;
for (int i = 0; i < n; i++) {
ans += ((s[i] - '0') * b[n - i - 1] * (i + 1)) % MOD;
ans %= MOD;
}
return ans;
}
int main () {
string n;
cin >> n;
cout << substrings (n) << endl;
}
// SOLUTION 3 - O(n) - more algorithms
#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
using namespace std;
const int MOD = 1000000007;
auto substrings (string s) {
int n = s.size ();
vector<long> a (n), b (n); a[0] = 1; // a = weight, b = weight sum
generate (a.begin () + 1, a.end (), [&, i = 1LL] () mutable { i *= 10; i %= MOD; return i; });
partial_sum (a.begin (), a.end (), b.begin (), [&](auto i, auto j) { return (i + j) % MOD; });
auto value_add_by_digit = [&, i = 0] (auto t, auto j) mutable {
++i; return (t + ((j - '0') * b[n - i] * i)) % MOD;
};
return accumulate (s.begin (), s.end (), 0LL, value_add_by_digit);
}
int main () {
string n;
cin >> n;
cout << substrings (n) << endl;
}