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.
题意:给定一个表达式。。可以改变该表达式的运算顺序,要求出该表达式可以计算出的最大值和最小值。
思路:贪心。。先加后乘为最大。先乘后加为最小。。有个注意点最多12个数。每个数最多20。所以要用long long不然WA。
代码:
#include <stdio.h>
#include <string.h>
int t;
long long Max, Min, num2[15];
int num1[15];
char fu[15];
int numm, numm2;
void init() {
numm = 0; Min = 0; Max = 1;
while (1) {
scanf("%d%c", &num1[numm], &fu[numm]);
numm ++;
if (fu[numm - 1] == '\n')
break;
}
}
void solve() {
numm2 = 0;
memset(num2, 0, sizeof(num2));
for (int i = 0; i < numm; i ++) {
num2[numm2] += num1[i];
if (fu[i] == '*')
numm2 ++;
}
for (int i = 0; i <= numm2; i ++)
Max *= num2[i];
numm2 = 0;
memset(num2, 0, sizeof(num2));
for (int i = 0; i < numm; i ++) {
if (num2[numm2] != 0)
num2[numm2] *= num1[i];
else
num2[numm2] = num1[i];
if (fu[i] == '+')
numm2 ++;
}
for (int i = 0; i <= numm2; i ++)
Min += num2[i];
printf("The maximum and minimum are %lld and %lld.\n", Max, Min);
}
int main() {
scanf("%d\n", &t);
while (t --) {
init();
solve();
}
return 0;
}