-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAHardAoshuProblem.cpp
127 lines (104 loc) · 2.5 KB
/
AHardAoshuProblem.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <memory>
#include <iomanip>
#include <numeric>
#include <functional>
#include <new>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <cctype>
#include <ctime>
template<typename T> T gcd(T a, T b) {
if(!b) return a;
return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
return a * b / gcd(a, b);
}
template<typename T> void chmin(T& a, T b) {
a = (a > b) ? b : a;
}
template<typename T> void chmax(T& a, T b) {
a = (a < b) ? b : a;
}
int in() {
int x;
scanf("%d", &x);
return x;
}
using namespace std;
typedef long long Int;
typedef unsigned uint;
int T, N;
string A, B, C;
int v[10];
int ans;
map<char, int> mp;
Int f(string& s) {
int i;
int id = 0;
Int ans = 0;
for (i = (int) s.size() - 1; i >= 0; i--) {
if (s.size() > 1 && i == 0 && v[mp[s[i]]] == 0) return -1LL;
ans += (Int) pow(10, id++) * v[mp[s[i]]];
}
return ans;
}
void dfs(int pos, int mask) {
if (pos == N) {
Int sa = f(A);
Int sb = f(B);
Int sum = f(C);
if (sa == -1LL || sb == -1LL || sum == -1LL) return;
if (sa + sb == sum) {
ans += 1;
}
if (sa - sb == sum) {
ans += 1;
}
if (sa * sb == sum) {
ans += 1;
}
if (sb != 0 && sum * sb == sa) {
ans += 1;
}
} else {
int i;
for (i = 0; i < 10; i++) if (!(mask & (1 << i))) {
v[pos] = i;
dfs(pos + 1, mask | (1 << i));
}
}
}
int main(void) {
T = in();
int i;
for ( ; T--; ) {
cin >> A >> B >> C;
set<char> s;
for (i = 0; i < (int) A.size(); i++) s.insert(A[i]);
for (i = 0; i < (int) B.size(); i++) s.insert(B[i]);
for (i = 0; i < (int) C.size(); i++) s.insert(C[i]);
int id = 0;
for(set<char>::iterator it = s.begin(); it != s.end(); it++) {
mp[*it] = id++;
}
N = (int) s.size();
ans = 0;
dfs(0, 0);
printf("%d\n", ans);
}
return 0;
}