一道c++算法题,不知道该怎么设计,求指导
用户可以输入n个数和目标D。
可使用的运算符限定于加号和乘号两种,且它们之间既没有优先级次序也不得使用括号(故计算总是按输入n个数的顺序及添加的运算符自左向右进行)。
一旦得不到目标D,希望知道一个能够通过这n个数得出的大于D的最小值。
【输入】
第一行两个正整数 N 和 D,分别表示数的个数和目标结果。第二行为 N 个数字,以空格分隔。
【输出】
若能得到D,则输出一个对应算式;否则输出No,以及大于D的最小值(最小值不存在则输出-1)。
【限制】1 ≤ N ≤ 24,1 ≤ D < 2^60
【输入样例1】
4 235
34 12 5 5
【输出样例1】
34+12*5+5
【输入样例2】
3 600
9 9 9
【输出样例2】
No
729
一道c++算法题,不知道该怎么设计,求指导
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
7条回答 默认 最新
- 艾秋 2022-08-28 12:18关注
花了点时间,用递归和减而治之的思想。
#include <iostream> #include <deque> using namespace std; void Generate(const deque<int64_t> &operands, int64_t D, deque<char> &operators, int64_t &result) { if (operands.size() == 1u) { if ((operands[0] >= D) && (result == -1) || (result > operands[0])) { result = operands[0]; } return; } // 加法运算 auto tmpOperands(operands); tmpOperands[1] += tmpOperands[0]; tmpOperands.pop_front(); operators.push_back('+'); Generate(tmpOperands, D, operators, result); if (result == D) { return; } operators.pop_back(); // 乘法运算 tmpOperands[0] = operands[0] * operands[1]; operators.push_back('*'); Generate(tmpOperands, D, operators, result); if (result != D) { operators.pop_back(); } } int main(int, char **) { int64_t N, D, i; cin >> N >> D; deque<int64_t> operands; for (i = 0; i < N; ++i) { int t; cin >> t; operands.push_back(t); } deque<char> operators; int64_t result = -1; Generate(operands, D, operators, result); if (result == D) { for (i = 0; i < N - 1; ++i) { cout << operands[i] << operators[i]; } cout << operands[i] << endl; } else { cout << "NO" << endl; cout << result << endl; } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度
- ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
- ¥15 ETLCloud 处理json多层级问题
- ¥15 matlab中使用gurobi时报错
- ¥15 这个主板怎么能扩出一两个sata口
- ¥15 不是,这到底错哪儿了😭
- ¥15 2020长安杯与连接网探
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么