无优先级运算问题
2015-12-05 10:22
381 查看
#include <iostream> #include <fstream> #include <queue> #include <cmath> using namespace std; const int MAX = 50; int num[MAX]; //输入的数 int n, m; //整数个数,目标数 char op[] = {' ', '+', '-', '*', '/'}; class Node { public: int dep; //当前层 int *num; //输入的数 bool *flag; //是否已经用过 int *oper; //1--'+', 2--'-', 3--'*', 4--'/' Node(int d) { dep = d; num = new int[n+1]; flag = new bool[n+1]; oper = new int[n+1]; } //深度小的先出队列 bool operator < (const Node &node) const { return dep >= node.dep; } }; priority_queue<Node> q; //判断是否得到解 bool found(Node node) { int temp = node.num[1]; for(int i=1; i<node.dep; i++) switch(node.oper[i]) { case 1: temp += node.num[i+1]; break; case 2: temp -= node.num[i+1]; break; case 3: temp *= node.num[i+1]; break; case 4: temp /= node.num[i+1]; break; } return temp == m; } //向优先队列中加入活结点 void addNode(int numIndex, int oper, Node enode) { int dep = enode.dep + 1; Node now(dep); for(int i=1; i<=n; i++) { now.num[i] = enode.num[i]; now.flag[i] = enode.flag[i]; now.oper[i] = enode.oper[i]; } now.num[dep] = num[ numIndex ]; now.flag[dep] = true; now.oper[dep] = oper; q.push(now); } //输出结果 void out(Node node) { cout << "\n最少无优先级运算次数为:" << node.dep-1 << endl; cout << "最优无优先级运算表达式为:" << endl; for(int i=1; i<node.dep; i++) cout << node.num[i] << op[ node.oper[i] ]; cout << node.num[i]; } bool search() { Node enode(0); for(int i=1; i<=n; i++) { enode.num[i] = 0; enode.flag[i] = false; enode.oper[i] = 0; } while(true) { if(found(enode)) { out(enode); return true; } else { for(int i=1; i<=n; i++) //数字 if(!enode.flag[i]) for(int j=1; j<=4; j++) //运算符 addNode(i, j, enode); } if(q.empty()) return false; else { enode = q.top(); q.pop(); } } } int main() { ifstream fin("无优先级运算.txt"); cout << "输入整数个数:"; fin >> n; cout << n << endl; cout << "输入目标数:"; fin >> m; cout << m << endl; cout << "输入各整数:\n"; for(int i=1; i<=n; i++) { fin >> num[i]; cout << num[i] << " "; } if(!search()) cout << "No Solution!"; cout << endl; cout << endl; fin.close(); return 0; }
相关文章推荐
- python mmap使用记录
- CCBPM高级开发之类设计与数据库设计命名规则
- 最佳调度问题
- 如何在高并发分布式系统中生成全局唯一Id
- 在HTML中用Javascript接收参数
- 黑马程序员——C基础---数组
- CLRS 10.4有根树的表示
- 安装Hadoop系列 — 安装Eclipse
- CCBPM高级开发之类设计与数据库设计命名规则
- ADO_NET 数据库连接字符串大全
- 布线问题
- CCBPM关于工作流引擎授权功能说明
- [LeetCode] Largest Rectangle in Histogram 解题思路
- AngularJs Cookies 操作
- 命名空间比较好的博客
- 圆排列问题
- js精度丢失解决办法
- maven项目配置Project Facets时further configuration available不出来问题
- js精度丢失解决办法
- 安装Hadoop系列 — 安装Hadoop