您的位置:首页 > 其它

UVA 10700 Camel trading

2013-01-26 22:06 375 查看
这道题关键是要搞清楚什么时候取得最大值,什么时候取得最小值,搞清楚这点问题基本上解决了(可以找一两个例子试试,就可以发现规律了),问题中最重要的是也是我没有注意到的一点,就是数据的范围,当用乘法很多时数据是非常大的,还有一点就是乘法和加法其实是有相同的操作的,所以可以把两个操作何为一体,提高代码的重用性。

代码如下:

#include <iostream>

#include<stack>

#include<stdio.h>

#include<string.h>

using namespace std;

char a[50];

int len;

//int findmin();

long long  findmaxmin(bool);

int main()

{

    int t;

    cin >> t;

    getchar();

    while(t--)

    {

       fgets(a,sizeof(a),stdin);

       len = strlen(a) - 1;

       cout << "The maximum and minimum are "<<  findmaxmin(1)<< " and " << findmaxmin(0) << "." << endl;

    }

    return 0;

}

long long  findmaxmin(bool f)

{

    int i;

    long long  sum = 0,k,l;

    stack<long long >s;

    stack<char>ch;

    char c,ch1;

    if(f)

    ch1 = '+';

    else

    ch1 = '*';

    for(i = 0; i < len;i++)

    {

        if(a[i] >= '0' && a[i] <= '9')

        {

            k = a[i] - '0';

            if(a[i+1] >= '0' && a[i+1 <= '9'])

            {

                i++;

                k = k*10 + a[i] - '0';

            }

            if(!ch.empty())

            {

                c = ch.top();

                if(c == ch1)

                {

                    ch.pop();

                    if(!s.empty())

                    {

                        l = s.top();

                        s.pop();

                        if(ch1 == '+')

                        sum = l+k;

                        else

                         sum = l*k;

                        s.push(sum);

                    }

                }

                else

                {

                    s.push(k);

                }

            }

            else

            {

                s.push(k);

            }

        }

        else

        {

            ch.push(a[i]);

        }

    }

    while(!ch.empty())

    {

        k = s.top();

        s.pop();

        l = s.top();

        s.pop();

        c = ch.top();

        ch.pop();

        if(c == '+')

        {

           sum = k+l;

           s.push(sum);

        }

        else

        {

            sum = k*l;

            s.push(sum);

        }

    }

    k = s.top();

    while(!s.empty())

      s.pop();

    return k;

}

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