Uva--10700(技巧)

2014-07-23 20:52:25

Problem E - Camel trading

Time Limit: 1 second

Background

Aroud 800 A.D., El Mamum, Calif of Baghdad was presented the formula 1+2*3*4+5, which had its origin in the financial accounts of a camel transaction. The formula lacked parenthesis and was ambiguous. So, he decided to ask savants to provide him with a method to find which interpretation is the most advantageous for him, depending on whether is is buying or selling the camels.

The Problem

You are commissioned by El Mamum to write a program that determines the maximum and minimum possible interpretation of a parenthesis-less expression.

Input

The input consists of an integer N, followed by N lines, each containing an expression. Each expression is composed of at most 12numbers, each ranging between 1 and 20, and separated by the sum and product operators + and *.

Output

For each given expression, the output will echo a line with the corresponding maximal and minimal interpretations, following the format given in the sample output.

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.

思路:我的思路比较简单暴力,逐个把数和运算符取出来放进两个数组,然后再逐个地取运算符进行运算。
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 int main(){
 7    long long N,len;
 8    char c;
 9    scanf("%lld",&N);
10    while(N--){
11        long long ans[20],num[20],op[20],cnt = 0,acnt;
12        c = 0;
13        memset(num,0,sizeof(num));
14        while(c != '\n'){
15             scanf("%lld%c",&num[cnt],&c);
16             if(c == '+') op[cnt++] = 1;
17             else if(c == '*') op[cnt++] = 2;
18        }
19        acnt = 0;
20        ans[0] = num[0];
21        for(int i = 0; i < cnt; ++i){
22            if(op[i] == 1)   ans[acnt] += num[i + 1];
23            else     ans[++acnt] = num[i + 1];
24        }
25        for(int i = 1; i <= acnt; ++i)
26             ans[i] *= ans[i - 1];
27        printf("The maximum and minimum are %lld and ",ans[acnt]);
28        acnt = 0;
29        ans[0] = num[0];
30        for(int i = 0; i < cnt; ++i){
31             if(op[i] == 2)
32                 ans[acnt] *= num[i + 1];
33             else
34                 ans[++acnt] = num[i + 1];
35        }
36        for(int i = 1; i <= acnt; ++i)
37             ans[i] += ans[i - 1];
38         printf("%lld.\n",ans[acnt]);
39    }
40    return 0;
41 }

 


posted @ 2014-07-23 20:54  Naturain  阅读(161)  评论(0编辑  收藏  举报