uva 10700 - Camel trading

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 12 numbers, 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.
開始想暴力回溯,但是看到minimum的值好像就是不加括號直接按原來順序計算的值,然後注意了下每個數字的取值範圍都是正的,不存在等於0和負數的情況於是就可以貪心了;
a+b*c=<(a+b)*c c=1時相等;也可以這麼理解,原本*的優先級就大於+,(a+b)+c,(a*b)+c,等於沒加,加括號的改變最後結果的是a*(b+c)這種類型,
又由於先+再乘一定大於等於先乘再+,max=先做所有加法,再求積;min=先做所有乘法,再求和;
 
#include<stdio.h>
#include<string.h>
int main()
{
 char ch,s[1000];
 int i,top,t,num;
 double min,max,stack[20];
 scanf("%d\n",&t);
 while (t--)
 {
  gets(s);
  i=0; top=0; ch='+'; stack[0]=0;
  while (s[i]!='\0')
  {
   num=0;
   while (s[i]>='0'&&s[i]<='9') {num=num*10+s[i]-'0';++i;}
   if (ch=='+') stack[++top]=num;
           else stack[top]*=num;
   if (s[i]!='\0') ch=s[i++];//最後一個是字符串結束符循環結束標誌,i不用+1;
  }
  min=0;
  for (i=1;i<=top;i++)
  min+=stack[i];
  i=0; top=0; ch='*'; stack[0]=1;
  while (s[i]!='\0')
  {
   num=0;
   while (s[i]>='0'&&s[i]<='9') {num=num*10+s[i]-'0';++i;}
   if (ch=='*') stack[++top]=num;
          else stack[top]+=num;
   if (s[i]!='\0') ch=s[i++];
  }
  max=1;
  for (i=1;i<=top;i++)
  max*=stack[i];
  printf("The maximum and minimum are %.0lf and %.0lf.\n",max,min);
 }
 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章