-
Notifications
You must be signed in to change notification settings - Fork 1
/
1307.口算难题.cpp
106 lines (99 loc) · 2.97 KB
/
1307.口算难题.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
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
98
99
100
101
102
103
104
105
106
#include "s.h"
/*
* @lc app=leetcode.cn id=1307 lang=cpp
*
* [1307] 口算难题
*/
// @lc code=start
class Solution {
private:
unordered_map<char, int> rep;
unordered_map<char, int> lead_zero;
bool used[10];
int carry[10];
public:
bool dfs(const vector<string>& words, const string& result, int pos, int id, int len) {
if (pos == len) {
return carry[pos] == 0;
}
else if (id < words.size()) {
int sz = words[id].size();
if (sz <= pos || rep[words[id][sz - pos - 1]] != -1) {
return dfs(words, result, pos, id + 1, len);
}
else {
char ch = words[id][sz - pos - 1];
for (int i = lead_zero[ch]; i < 10; ++i) {
if (!used[i]) {
used[i] = true;
rep[ch] = i;
bool check = dfs(words, result, pos, id + 1, len);
used[i] = false;
rep[ch] = -1;
if (check) {
return true;
}
}
}
}
return false;
}
else {
int left = carry[pos];
for (const string& word: words) {
if (word.size() > pos) {
left += rep[word[word.size() - pos - 1]];
}
}
carry[pos + 1] = left / 10;
left %= 10;
char ch = result[result.size() - pos - 1];
if (rep[ch] == left) {
return dfs(words, result, pos + 1, 0, len);
}
else if (rep[ch] == -1 && !used[left] && !(lead_zero[ch] == 1 && left == 0)) {
used[left] = true;
rep[ch] = left;
bool check = dfs(words, result, pos + 1, 0, len);
used[left] = false;
rep[ch] = -1;
return check;
}
else {
return false;
}
}
}
bool isSolvable(vector<string>& words, string result) {
memset(used, false, sizeof(used));
memset(carry, 0, sizeof(carry));
for (string& word: words) {
if (word.size() > result.size()) {
return false;
}
for (char& ch: word) {
rep[ch] = -1;
lead_zero[ch] = max(lead_zero[ch], 0);
}
if (word.size() > 1) {
lead_zero[word[0]] = 1;
}
}
for (char& ch: result) {
rep[ch] = -1;
lead_zero[ch] = max(lead_zero[ch], 0);
}
if (result.size() > 1) {
lead_zero[result[0]] = 1;
}
return dfs(words, result, 0, 0, result.size());
}
};
// @lc code=end
int main(){
Solution s;
vector<string> words={
"SEND","MORE"
};
cout << s.isSolvable(words, "MONEY");
}