aboutsummaryrefslogtreecommitdiff
path: root/2024/07/day07b.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2024/07/day07b.cpp')
-rw-r--r--2024/07/day07b.cpp51
1 files changed, 51 insertions, 0 deletions
diff --git a/2024/07/day07b.cpp b/2024/07/day07b.cpp
new file mode 100644
index 0000000..1c2d900
--- /dev/null
+++ b/2024/07/day07b.cpp
@@ -0,0 +1,51 @@
1#include <algorithm>
2#include <iostream>
3#include <sstream>
4#include <string>
5#include <string_view>
6#include <vector>
7using namespace std;
8
9long long uncat(long long x, long long y) {
10 if (y == 0)
11 return x % 10 == 0 ? x / 10 : -1;
12 while (y > 0) {
13 if (x % 10 != y % 10)
14 return -1;
15 x /= 10;
16 y /= 10;
17 }
18 return x;
19}
20
21bool possible(long long x, vector<long long>& a, int i) {
22 if (i == 0)
23 return a[0] == x;
24
25 bool p = possible(x-a[i], a, i-1);
26 if (a[i] != 0 && x % a[i] == 0)
27 p = p || possible(x/a[i], a, i-1);
28 auto u = uncat(x, a[i]);
29 if (u != -1)
30 p = p || possible(u, a, i-1);
31 return p;
32}
33
34int main() {
35 string line;
36 long long tot = 0;
37 while (getline(cin, line)) {
38 long long x, i;
39 vector<long long> a;
40 stringstream s(line);
41 s >> x;
42 char colon;
43 s >> colon;
44 while (s >> i)
45 a.push_back(i);
46 if (possible(x, a, a.size()-1))
47 tot += x;
48 }
49 cout << tot << endl;
50 return 0;
51}

Generated with cgit - Back to sebastiano.tronto.net