-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypt_arithmetic.cpp
71 lines (63 loc) · 1.77 KB
/
crypt_arithmetic.cpp
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
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int getNumber(string s, unordered_map<char, int>& hm) {
string num = "";
for (int i = 0; i < s.length(); i++) {
num += to_string(hm[s[i]]);
}
return stoi(num);
}
void solve(int i, string unique, unordered_map<char, int>& hm, vector<bool>& used, vector<string>& words, string result) {
if (i == unique.length()) {
int sum = 0;
for (const string& s : words) {
sum += getNumber(s, hm);
}
int r = getNumber(result, hm);
if (sum == r) {
for (int k = 0; k <= 25; k++) {
char ch = static_cast<char>('A' + k);
if (hm.find(ch) != hm.end()) {
cout << ch << " -> " << hm[ch] << " ";
}
}
cout << endl;
}
return;
}
char ch = unique[i];
for (int j = 0; j <= 9; j++) {
if (!used[j]) {
hm[ch] = j;
used[j] = true;
solve(i + 1, unique, hm, used, words, result);
hm[ch] = -1;
used[j] = false;
}
}
}
int main() {
vector<string> words = {"SEND", "MORE"};
string result = "MONEY";
unordered_map<char, int> hm;
string unique = "";
for (const string& s : words) {
for (char ch : s) {
if (hm.find(ch) == hm.end()) {
hm[ch] = -1;
unique += ch;
}
}
}
for (char ch : result) {
if (hm.find(ch) == hm.end()) {
hm[ch] = -1;
unique += ch;
}
}
vector<bool> used(10, false);
solve(0, unique, hm, used, words, result);
return 0;
}