uva10700- Camel trading

来源:互联网 发布:北京科瑞明软件招聘 编辑:程序博客网 时间:2024/04/30 20:28

Sample Input
3
1+2*3*4+5
4*18+14+7*10
3+11+4*1*13*12*8+3*3+8
Sample Output
The maximum and minimum are 81 and 30.
The maximum and minimum are 1560 and 156.
The maximum and minimum are 339768 and 5023.
题意:
如上,给你一个带‘+’和‘*’的表达式,求最大和最小值
思路:
最大值:先加后乘
最小值:先乘后加
因为 : (a+b)*c a+b*c
->a*c+b*c a+b*c
都是正整数,显然先加后乘更大。

代码如下:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 1005;char str[N];long long  num[N];char op[N];int len, lop, lnum;void init() {    lop = 0, lnum = 0;    for (int i = 0; i < len;) {        if (str[i] == '+' || str[i] == '*') {            op[lop++] = str[i];            i++;        }        else {            long long  number = 0;            while (str[i] >= '0'&&str[i] <= '9') {                number = number * 10 + (str[i] - '0');                i++;            }            num[lnum++] = number;        }    }    /*for (int i = 0; i < lop; i++)    printf("%c\t", op[i]);    printf("\n");    for (int i = 0; i < lnum; i++)    printf("%d\t", num[i]);    printf("\n");*/}long long  get_min() {    long long  temp[N];    long long  minn = 0;    for (int i = 0; i < lnum; i++)        temp[i] = num[i];    for (int i = 0; i < lop; i++) {        if (op[i] == '*') {            temp[i + 1] *= temp[i];            temp[i] = 0;        }    }    for (int i = 0; i < lnum; i++) {        minn += temp[i];    }    return minn;}long long  get_max() {    long long temp[N];    long long maxn = 1;    for (int i = 0; i < lnum; i++)        temp[i] = num[i];    for (int i = 0; i < lop; i++) {        if (op[i] == '+') {            temp[i + 1] += temp[i];            temp[i] = 0;        }    }    for (int i = 0; i < lnum; i++) {        if (temp[i] != 0)            maxn *= temp[i];    }    return maxn;}int main() {    int cas;    scanf("%d\n", &cas);    while (cas--) {        gets(str);        len = strlen(str);        init();        long long minn = get_min();        long long maxn = get_max();        printf("The maximum and minimum are %lld and %lld.\n", maxn, minn);    }    return 0;}
0 0