题意理解
这题首先想到,显然有四根火柴是用来摆出“+=”的。
然后观察一下这些数字分别需要多少根火柴:
数字 | 需要的火柴数 |
---|---|
0 | 6 |
1 | 2 |
2 | 5 |
3 | 5 |
4 | 4 |
5 | 5 |
6 | 6 |
7 | 3 |
8 | 7 |
9 | 6 |
然后我就在想,最多有24根火柴用来摆等式,也就是20根火柴用来摆数字。一个三位数加一个一位数等于一个三位数,简单构造一下,111+0=111是在20根以内的。而如果用到了四位数,则必定有9个数字,应该是摆不下来了。所以最多的话是一个999*999的循环,然而还可以进行各种优化,比如限定最多有七位数字。然后就是考虑一下重复的问题。于是我决定按照这个思路来搞一下。然后就过掉了。这不是在忽悠人嘛,这么简单,我还以为真的需要回溯什么的。
后来我认真想了一下,好像没有必要判断重复,应该是我失了智。。。那也就是说,这题就是用来骗傻子的。。。根本不需要花里胡哨,直接来段python代码简单说明一下情况,至于为什么连优化也省略掉呢?因为哪怕就是不优化,量级也很小。
for i in range(1, 1000):
for j in range(1, 1000):
if matches(i) + matches(j) + matches(i+j) + 4 == n:
cnt += 1
代码
#include <cstring>
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include <vector>
#include <set>
#include <sstream>
#include <utility>
using namespace std;
const int costs[] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
void read(int &x) {
x = 0;
int f = 1;
char ch = getchar();
while(ch > '9'||ch < '0') {
if(ch == '-') {
f = -1;
}
ch = getchar();
}
while(ch >= '0' && ch <= '9') {
x = x * 10 + (int)(ch - 48);
ch = getchar();
}
x = x * f;
}
string itos(int x) {
stringstream ss;
ss << x;
return ss.str();
}
int get_cost(int x) {
if(x == 0) {
return 6;
}
int cost = 0;
while(x != 0) {
cost += costs[x % 10];
x /= 10;
}
return cost;
}
int main() {
int n;
read(n);
if(n <= 10) {
cout << "0";
return 0;
}
int left;
int right;
set<pair<int, int> > equations;
int cnt = 0;
for(left = 0; left < 1000; left++) {
for(right = 0; right < 1000; right++) {
int result = left + right;
bool exceed_length = (itos(left).length() + itos(right).length() + itos(result).length()) > 7;
if(exceed_length) {
break;
}
if(get_cost(left) + get_cost(right) + get_cost(result) + 4 == n) {
if(equations.find(pair<int, int>(left, right)) == equations.end()) {
equations.insert(pair<int, int>(left, right));
cnt++;
}
}
}
}
cout << cnt;
return 0;
}
欢迎加入“不会算法一群菜鸟”,群号是⑥⑥①⑨②2025,这是我设置的一道很低的门槛用来阻止广告的。入群的验证暗号是:我爱编译原理