day07b.cpp (913B)
1 #include <algorithm> 2 #include <iostream> 3 #include <sstream> 4 #include <string> 5 #include <string_view> 6 #include <vector> 7 using namespace std; 8 9 long 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 21 bool 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 34 int 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 }