Camel trading - UVa 10700 dp
2015-02-28 14:21
316 查看
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 decidedto 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.
题意:通过添加括号改变运算顺序,求最后结果的最大值和最小值。
思路:简单的dp,dp[i][j]=max(dp[i][k] *+ dp[k+1][j])。注意最后结果用long long.
AC代码如下:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long ll; int T,t,n; char s[100010],type[1010]; ll dp[1010][1010],num[1010],maxn,minn,INF=1e18; void init() { int i,j,k=0,len=strlen(s); n=0; for(i=0;i<=len;i++) { if(s[i]=='*' || s[i]=='+' || s[i]=='\0') { num[++n]=k; k=0; type =s[i]; } else { k=k*10+s[i]-'0'; } } } int main() { int i,j,k,p; scanf("%d",&T); for(t=1;t<=T;t++) { scanf("%s",s); init(); for(i=1;i<=n;i++) dp[i][i]=num[i]; for(p=1;p<=n;p++) for(i=1;i+p<=n;i++) { j=i+p; dp[i][j]=0; for(k=i;k<j;k++) { if(type[k]=='*') dp[i][j]=max(dp[i][j],dp[i][k]*dp[k+1][j]); else dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]); } } maxn=dp[1] ; for(p=1;p<=n;p++) for(i=1;i+p<=n;i++) { j=i+p; dp[i][j]=INF; for(k=i;k<j;k++) { if(type[k]=='*') dp[i][j]=min(dp[i][j],dp[i][k]*dp[k+1][j]); else dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]); } } minn=dp[1] ; printf("The maximum and minimum are %lld and %lld.\n",maxn,minn); } }
相关文章推荐
- UVA 10700 Camel trading(计算式子加减乘除的优先级处理)
- UVa 10700 Camel trading (计算表达式)
- UVA - 10700 Camel trading(贪心+栈)
- uva:10700 - Camel trading(贪心)
- uva - 10700 - Camel trading(贪心)
- UVA10700:Camel trading(栈和队列)
- uva:10700 - Camel trading(贪婪)
- uva 10700 Camel trading(STL 栈)
- uva10700 - Camel trading(无括号的表达式)
- UVA 10700 Camel trading(贪心)
- UVa 10700 Camel trading(计算式最大和最小值)
- UVA 10700-Camel trading(栈求表达式的最大最小值)
- uva 10700 Camel trading (模拟栈)
- UVA - 10271 Chopsticks DP
- UVA 11404 - Palindromic Subsequence(LCS和DP两种做法)
- Uva11021 tribbles 概率dp
- (UVA - 11400)Lighting System Design(DP)
- 条件DP UVA 672 Gangsters
- dp(UVa 10604 - Chemical Reaction)
- UVA 10131 Is Bigger Smarter? DP