noip火柴棍等式

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

注意:

1. 加号与等号各自需要两根火柴棍

2. 如果A≠B,则A+B=C与B+A=C视为不同的等式(A、B、C>=0)

3. n根火柴棍必须全部用上

火柴棍等式

输入文件共一行,又一个整数n(n<=24)。

输出文件共一行,表示能拼成的不同等式的数目。

样例1:

14

 

样例2:

18

样例1:

2

 

样例2:

9


比较好想的一种解
#include
using namespace std;

int main()
{ 
     int a,b,n,ans=0,i,j=0;
	 int huochai[20000]={6,2,5,5,4,5,6,3,7,6};//0-9每个数字需要的火柴
	 int num[5]={0};
	 //先算出10-19999所有数字需要的火柴
	 for(i=10;i<=19999;i++)
	 {
		 int tmp=i;
	     j=0;
		 huochai[i]=0;
		 while(tmp)
		 {
			 num[j]=tmp%10;
			 tmp/=10;
			 j++;
		 }
		 for(tmp=0;tmp>n;
	 //穷举a+b=c的所有等式,根据之前算出的数组计算火柴数,找出符合条件的
     for(a=0;a<=10000;a++)
	 {
		 if(huochai[a]>n-8)
			 continue;
		 for(b=0;b<=10000;b++)
		 {
			 if(huochai[b]>n-8)
				 continue;
				   if(huochai[a]+huochai[b]+huochai[a+b]+4==n)
				   {
					   cout<
### 关于NOIP 2008 火柴等式 #### 题目内容 给定 n 根火柴棍,可以拼出多少个形如 “A + B = C” 的等式?其中 A、B 和 C 是由火柴棍拼成的整数(如果这些数是非零数值,则其最高位不可为零)。具体来说,用火柴棍拼写数字 0 到 9 所需的数量如下表所示: | 数字 | 使用火柴数量 | | --- | --------------| | 0 | 6 | | 1 | 2 | | 2 | 5 | | 3 | 5 | | 4 | 4 | | 5 | 5 | | 6 | 6 | | 7 | 3 | | 8 | 7 | | 9 | 6 | 输入仅有一个正整数 n (n ≤ 24),表示可用的火柴总数。 输出应是一个整数,代表能组成的合法等式的数目[^1]。 #### 解题思路 对于这个问题,核心在于枚举所有可能构成的有效组合。由于题目规定了最大火柴数不超过24根,因此可以直接通过预处理的方式计算每一个数字所需消耗的火柴量,并基于此构建动态规划模型来进行求解。 为了简化问题复杂度,在实际编程实现过程中通常会采用记忆化搜索的方法来避免重复运算。这种方法能够有效地减少不必要的计算次数,从而提升程序效率。另外需要注意的是,因为涉及到加法操作,所以还需要考虑进位的情况以及如何合理分配剩余的火柴用于表达其他部分的结果。 ```python # Python code snippet to solve the matchstick equation problem. def count_equations(n): # Define a dictionary mapping each digit to its corresponding number of matches required. digits_to_matches = {str(i): v for i, v in enumerate([6, 2, 5, 5, 4, 5, 6, 3, 7, 6])} @functools.lru_cache(None) def dfs(a, b, c, remaining): if remaining < 0: return 0 if not a and not b and not c: return int(remaining == 0) result = 0 max_digit = min(int(bool(a)), int(bool(b)), int(bool(c))) for d in range(max_digit, 10): new_remaining = ( remaining - digits_to_matches[str(d)] * sum((a > 0, b > 0, c > 0)) + ((d >= 5) << bool(a & b)) ) result += dfs( a - (d != 0), b - (d != 0), c - (d != 0 or (not a and not b)), new_remaining, ) return result total_ways = 0 for first_num_len in range(1, n//2+1): for second_num_len in range(1, n-first_num_len+1): third_num_len = n - first_num_len - second_num_len if any(x <= 0 for x in [first_num_len, second_num_len, third_num_len]): continue total_ways += dfs(first_num_len, second_num_len, third_num_len, n-sum(digits_to_matches.values())) return total_ways if __name__ == "__main__": import functools print(count_equations(int(input()))) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值