您的位置:首页 > 其它

无优先级运算问题

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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: