火柴棒等式
https://www.luogu.com.cn/problem/P1149
这个题可以不用搜索直接枚举就可以,方法很简单,但是不容易想到
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int arr[10] = { 6,2,5,5,4,5,6,3,7,6 };
int num(int x) {
int sum = 0;
if (x == 0)
return 6;
while (x != 0) {
sum += arr[x % 10];
x /= 10;
}
return sum;
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
int n;
cin >> n;
int sum = 0;
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if (num(i) + num(j) + 4 + num(i + j)==n) {
sum++;
}
}
}
cout << sum << endl;
return 0;
}
另一个我比较认可的方法就是回溯法,每个可能的结果都尝试一遍
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int arr[1000] = { 6,2,5,5,4,5,6,3,7,6 };
int b[4];
int n, total;
int num(int x) {
int sum = 0;
while (x != 0) {
sum += arr[x % 10];
x /= 10;
}
return sum;
}
void search(int t) {//回溯法
for (int i = 0; i < 1000; i++) {
if (arr[i] <= n) {//火柴棍还足够
n = n - arr[i];//尝试
b[t] = i;
if (t == 3) {
if (n == 0 && b[1] + b[2] == b[3]) {//条件要写全
total++;
}
}
else
search(t + 1);//试探
n = n + arr[i];//退回
//b[t] = 0;可省
}
}
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
cin >> n;
n = n - 4;
for (int i = 10; i < 1000; i++)
arr[i] = num(i);
search(1);
cout << total << endl;
return 0;
}