aboutsummaryrefslogtreecommitdiff
path: root/2024/07/day07b.cpp
blob: 1c2d900977f7c107f64fd42b613e0e069a47042a (plain)
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
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
using namespace std;

long long uncat(long long x, long long y) {
	if (y == 0)
		return x % 10 == 0 ? x / 10 : -1;
	while (y > 0) {
		if (x % 10 != y % 10)
			return -1;
		x /= 10;
		y /= 10;
	}
	return x;
}

bool possible(long long x, vector<long long>& a, int i) {
	if (i == 0)
		return a[0] == x;

	bool p = possible(x-a[i], a, i-1);
	if (a[i] != 0 && x % a[i] == 0)
		p = p || possible(x/a[i], a, i-1);
	auto u = uncat(x, a[i]);
	if (u != -1)
		p = p || possible(u, a, i-1);
	return p;
}

int main() {
	string line;
	long long tot = 0;
	while (getline(cin, line)) {
		long long x, i;
		vector<long long> a;
		stringstream s(line);
		s >> x;
		char colon;
		s >> colon;
		while (s >> i)
			a.push_back(i);
		if (possible(x, a, a.size()-1))
			tot += x;
	}
	cout << tot << endl;
	return 0;
}

Generated with cgit - Back to sebastiano.tronto.net