P1149 [NOIP2008 提高组] 火柴棒等式

题目描述

给你 n n n 根火柴棍,你可以拼出多少个形如 A + B = C A+B=C A+B=C 的等式?等式中的 A A A B B B C C C 是用火柴棍拼出的整数(若该数非零,则最高位不能是 0 0 0)。用火柴棍拼数字 0 ∼ 9 0\sim9 09 的拼法如图所示:

注意:

  1. 加号与等号各自需要两根火柴棍;
  2. 如果 A ≠ B A\neq B A=B,则 A + B = C A+B=C A+B=C B + A = C B+A=C B+A=C 视为不同的等式( A , B , C ≥ 0 A,B,C\geq0 A,B,C0);
  3. n n n 根火柴棍必须全部用上。

输入格式

一个整数 n ( 1 ≤ n ≤ 24 ) n(1 \leq n\leq 24) n(1n24)

输出格式

一个整数,能拼成的不同等式的数目。

样例 #1

样例输入 #1

14

样例输出 #1

2

样例 #2

样例输入 #2

18

样例输出 #2

9

提示

【输入输出样例 1 解释】

2 2 2 个等式为 0 + 1 = 1 0+1=1 0+1=1 1 + 0 = 1 1+0=1 1+0=1

【输入输出样例 2 解释】

9 9 9 个等式为

0 + 4 = 4 0+4=4 0+4=4 0 + 11 = 11 0+11=11 0+11=11 1 + 10 = 11 1+10=11 1+10=11 2 + 2 = 4 2+2=4 2+2=4 2 + 7 = 9 2+7=9 2+7=9 4 + 0 = 4 4+0=4 4+0=4 7 + 2 = 9 7+2=9 7+2=9 10 + 1 = 11 10+1=11 10+1=11 11 + 0 = 11 11+0=11 11+0=11

noip2008 提高第二题

思路

1. 暴力枚举
2. 回溯法
参考大佬题解。具体见下方代码及其注释。

代码

1. 暴力枚举

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#define endl '\n'
using namespace std;

int n;

// 存储每个数字所需的火柴数
// 只枚举到1000是因为1000 + () = ()就已经24根火柴了,n最大到24
int a[1000] = { 6,2,5,5,4,5,6,3,7,6 };

int main() {
	ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
	cin >> n;

	// 计算出每个数字所需的火柴数
	for (int i = 10; i <= 999; i++) {

		// 这里真的很巧妙,在算两位数的时候用到一位数
		// 而算三位数的时候,无需分解每一位,只需把他看作前两位和后一位相加
		a[i] = a[i / 10] + a[i % 10];
	}

	int ans = 0;
	for (int i = 0; i <= 999; i++) {
		for (int j = 0; j <= 999; j++) {

			// 注意这个if不能漏,否则当i+j超过1000时,会发生下标越界,而且>1000本身也没有意义了
			if (i + j >= 1000) {
				continue;
			}

			if (a[i] + a[j] + a[i + j] + 4 == n) {
				// 用于debug
				//cout << i << " " << j << " " << i + j << endl;
				//cout << a[i] << " " << a[j] << " " << a[i + j] << endl;
				ans++;
			}
		}
	}

	cout << ans << endl;
	return 0;
}

2. 回溯法

这里的回溯法主要是要掌握这种思想。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#define endl '\n'
using namespace std;

int n;
int a[1000] = { 6,2,5,5,4,5,6,3,7,6 };
vector<int> path;
int ans;

void dfs(int sum) {

	// 只需递归两层,枚举两个加数即可,和自动算出
	if (path.size() == 2) {
		int res = 0;

		res += a[path[0]];
		res += a[path[1]];
		res += a[path[0] + path[1]];

		if (res == n) {
			ans++;
		}
		return;
	}

	for (int i = 0; sum + i <= 999; i++) {// sum+i<=999 相当于剪枝吧
		path.push_back(i);
		sum += i;
		dfs(sum);
		path.pop_back();
		sum -= i;
	}
}

int main() {
	ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
	cin >> n;

	n = n - 4;// 去掉加号和等号的4根火柴

	for (int i = 10; i <= 999; i++) {
		a[i] = a[i / 10] + a[i % 10];
	}

	dfs(0);

	cout << ans << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值