UVA - 10700
| Time Limit: 3000MS | Memory Limit: Unknown | 64bit IO Format: %lld & %llu |
Description
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.
You are commissioned by El Mamum to write a program that determines the maximum and minimum possible interpretation of a parenthesis-less expression.
The input consists of an integer N, followed by N lines, each containing an expression. Each expression is composed of at most 12 numbers, each ranging between 1 and 20, and separated by the sum and product operators +and *.
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.
3 1+2*3*4+5 4*18+14+7*10 3+11+4*1*13*12*8+3*3+8
The maximum and minimum are 81 and 30. The maximum and minimum are 1560 and 156. The maximum and minimum are 339768 and 5023.
Source
思路:很明显,当加法优于乘法先算出时有最大,乘法先算出时有最小
AC代码(略挫,没用stack写):
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>
#define LL long long
using namespace std;
int N;
char str[100];
LL ope[20];
LL num[20];
LL sum, osum;
LL fun(char s[], int n) { //字符串转换为数字
LL tmp = 0, cnt = 0;
for(int i = n; isdigit(s[i]); i++) {
tmp = tmp * 10 + (s[i] - '0');
cnt ++;
}
num[sum++] = tmp;
return cnt - 1;
}
int main() {
scanf("%d", &N);
while(N--) {
sum = osum = 0;
memset(num, 0, sizeof(num));
memset(ope, 0, sizeof(ope));
scanf("%s", str);
for(int i = 0; str[i] != '\0'; i++) {
if(isdigit(str[i])) {
i += fun(str, i);
}
else
{
if(str[i] == '*') ope[osum++] = 0;
else ope[osum++] = 1;
}
}
//for(int i = 0; i < sum; i++) printf("%d ", num[i]);
//printf("\n");
//for(int i = 0; i < osum; i++) printf("%d ", ope[i]);
//printf("\n");
LL MAX = 1, MIN = 0;
//找最小
LL tnum[20];
for(int i = 0; i < 20; i++) tnum[i] = num[i];
for(int i = 0; i < osum; i++) {
if(ope[i] == 0) {
int t = i;
LL tmp = tnum[i] * tnum[i + 1];
tnum[i + 1] = 0;
for(int j = i + 1; j < osum && ope[j] == 0; j++) {
tmp *= tnum[j + 1];
i = j;
tnum[j + 1] = 0;
}
tnum[t] = tmp;
}
}
//for(int i= 0; i < sum; i++) printf("%d ", tnum[i]);
for(int i = 0; i < sum; i++) MIN += tnum[i];
//找最大
for(int i = 0; i < osum; i++) {
if(ope[i] == 1) {
int t = i;
LL tmp = num[i] + num[i + 1];
num[i + 1] = 1;
for(int j = i + 1; j < osum && ope[j] == 1; j++) {
tmp += num[j + 1];
i = j;
num[j + 1] = 1;
}
num[t] = tmp;
}
}
for(int i = 0; i < sum; i++) MAX *= num[i];
printf("The maximum and minimum are %lld and %lld.\n", MAX, MIN);
}
return 0;
}
UVA - 10700 - Camel trading (简单贪心)
原文:http://blog.csdn.net/u014355480/article/details/44761205