HEU 百题解3201 最大值
最大值
TimeLimit: 1 Second MemoryLimit: 64 Megabyte
Description
给你一个表达式,你可以通过在不同的地方添加括号从而改变式子的结果。比如1 + 2 * 3,如果是(1+2)*3结果是9,如果是1+2*3,结果是7,现在给你一个这样的式子,保证只有乘法和加法,但是也许会出现负数,求出这个式子通过不同的加括号方式,所能求得的最大结果。
Input
多组数据,每组数据第一行给出一个整数N(2<=N<=100),是所给式子的整数个数,下面包含表达式,所有整数和符号之间都会相隔一个空格。
Output
对于每组测试数据输出一个给出式子能算出的最大值。
Sample Input
4 1 + 2 * 3 + -1
Sample Output
8
动态规划题:表达式加括号
易错点:由于输入的数中存在负数,因此可能会出现两个负数相乘得到一个很大整数的情况,因此在记录是不仅要记录最大值,还要记录最小值
心得:使用结构体作为函数返回对象即可返回多个值~~
第一次自己做动态规划题,除了上面说的两个负数相乘问题忘了考虑,其他的状态转移都搞出来了(虽然是道水题),还是不错滴~~
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstring> 3 #include<vector> 4 5 #define MAX 2000000000 6 #define MIN -2000000000 7 8 using namespace std; 9 10 typedef struct sth 11 { 12 long max; 13 long min; 14 } data; 15 16 vector<int> num; 17 vector<char> s; 18 data dp[100][100]; 19 20 data cmp(int a,int b,int c,int d) 21 { 22 data x; 23 int temp; 24 x.max=MIN; 25 x.min=MAX; 26 if((temp=(a*c))>x.max) 27 x.max=temp; 28 else if(temp<x.min) 29 x.min=temp; 30 if((temp=(a*d))>x.max) 31 x.max=temp; 32 else if(temp<x.min) 33 x.min=temp; 34 if((temp=(b*c))>x.max) 35 x.max=temp; 36 else if(temp<x.min) 37 x.min=temp; 38 if((temp=(b*d))>x.max) 39 x.max=temp; 40 else if(temp<x.min) 41 x.min=temp; 42 return x; 43 } 44 45 data f(int m,int n) 46 { 47 if(dp[m][n].max!=MIN&&dp[m][n].min!=MAX) 48 return dp[m][n]; 49 if(m==n) 50 { 51 dp[m][n].max=dp[m][n].min=num[m]; 52 return dp[m][n]; 53 } 54 for(int i=m;i<n;i++) 55 { 56 if(s[i]=='+') 57 { 58 int temp=f(m,i).max+f(i+1,n).max; 59 if(dp[m][n].max<temp) 60 dp[m][n].max=temp; 61 temp=f(m,i).min+f(i+1,n).min; 62 if(dp[m][n].min>temp) 63 dp[m][n].min=temp; 64 } 65 else if(s[i]=='*') 66 { 67 data temp=cmp(f(m,i).max,f(m,i).min,f(i+1,n).max,f(i+1,n).min); 68 if(temp.max>dp[m][n].max) 69 dp[m][n].max=temp.max; 70 if(temp.min<dp[m][n].min) 71 dp[m][n].min=temp.min; 72 } 73 } 74 return dp[m][n]; 75 } 76 77 78 int main() 79 { 80 int n; 81 while(cin>>n) 82 { 83 int tempint; 84 85 s.clear(); 86 num.clear(); 87 for(int i=0;i<100;i++) 88 for(int j=0;j<100;j++) 89 { 90 dp[i][j].max=MIN; 91 dp[i][j].min=MAX; 92 } 93 94 for(int i=1;i<n;i++) 95 { 96 char tempchar; 97 cin>>tempint>>tempchar; 98 num.push_back(tempint); 99 s.push_back(tempchar); 100 } 101 cin>>tempint; 102 num.push_back(tempint); 103 cout<<f(0,n-1).max<<endl; 104 } 105 106 return 0; 107 }