无优先级运算问题

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

这里写图片描述

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值