ZOJ-1014-Operand

这题是字符串操作题:题意比较好理解,没有固定的模板,算法思想就是对于操作浮,从+,,^,一个一个遍历字符串,存在其中的一个就说明,以该操作浮将其划分为n个操作数,时间复杂度O(3n)。需要注意括号的操作,即括号的比配问题。
此处还用到了C语言的模板list 容器,或stack 容器,该处对于输入的格式由于不知道每次的操作步数,所以需要加入cin.peek()!=’\n’来判断是否输入结束。因而需要在前后加入cin.ignore() 用来跳过换行浮。

#include<iostream>
#include<list>
#include<sstream>
#include<cstdio>
 
using namespace std;
 
char optSign[3] = {'+', '*', '^'};
 
string Operand(int n, string s)
{
    int Count;
    int bracket;
    bool found;
    string answer = "";
 
    for (int i=0; i<3; i++)//三个运算符按优先线划分表达式 
    {
        Count = 1;
        bracket = 0;
        found = false;
        answer = "";
 
        for (int j=0; j<s.length(); j++)
        {
            answer += s[j];
            if (s[j] == '(')
            {
                bracket++;
                continue;
            }
            else if (s[j] == ')')
            {
                bracket--;
                continue;
            }
            else if (bracket) //还在括号里 
                continue;
            else if (s[j] != optSign[i])
                continue;
            else
            {
                if (Count == n)
                    return answer.substr(0,answer.length() - 1);
                else
                {
                    found = true;
                    answer = "";
                    Count++;
                }
            }
        }
        if (found)//此时找到运算浮,但是为空 
            return answer;
    }
    if (s[0] == '(')//外面第一个是括号 
        return s.substr(1,s.length() - 2);
    else
        return s;//没有运算浮 
}
 
int main()
{
	//freopen("tmp.txt", "r", stdin);
    int n;
    string src;
    char ename;
    bool lineFlag = true;
    list<int> question;
 
    while (cin>>src && src!="*")
    {
        if (lineFlag)
            lineFlag = false;
        else
            cout<<endl;
        ename = src[0];
        src = src.substr(3);
        cout<<"Expression "<<ename<<":"<<endl;
        cin>>n;
        cin.ignore();//丢掉换行符 
        while (n--)
        {
            int num;
            string ops = src;
            question.clear();
            while (cin.peek() != '\n')
            {
                cin>>num;
                question.push_back(num);
                ops = Operand(num,ops);
            }
            cin.ignore();
            int len = question.size();
            while (!question.empty())
            {
                int n = question.back();
                question.pop_back();
                cout<<"op("<<n<<",";
            }
            cout<<ename;
            for (int i=1; i<=len; i++)
                cout<<")";
            cout<<"="<<ops<<endl;
        }
    }
 
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值