Polygon game (DP)

Description Polygon game is a game played by...

Description

Polygon game is a game played by one person. At the beginning, there is a polygon composed of n vertices. Each vertex is assigned an integer value, and each edge is assigned an operator "+" or "*". All edges are sequentially numbered from 1 to n with integers.

Step 1 of the game, delete one side.

The next n-1 steps are as follows:

(1) Select an edge e and two vertices V1 and V2 connected by E;

(2) Replace edge e with a new vertex and two vertices V1 and V2 connected by E. The integral values of vertices V1 and V2 are assigned to the new vertex through the operation on edge E.

Finally, all sides are removed and the game is over. The score of the game is the integer value on the remaining vertex.

Problem: for a given polygon, calculate the highest score w (- 231 < w < 231).

Input

The first line of input is a single integer n (3 ≤ n ≤ 18), which represents the number of vertices (and also the number of sides) of the polygon. Next line n, each line contains an operator ("+" or "*") and an integer V[i] (- 10 < V[i] < 10), representing the operator corresponding to the i-th edge and the value on the i-th vertex, respectively.

Output

The output has only one integer representing the highest score W.

Sample Input

3
+ 2
* 3
+ 1

Sample Output

9

#include<string.h> #include<stdio.h> #include<iostream> #define MAX 102 using namespace std; int v[MAX]; char op[MAX]; int n,minf,maxf; int m[MAX][MAX][2]; void minMax(int i,int s,int j) { int e[5]; int a=m[i][s][0], b=m[i][s][1], r=(i+s-1)%n+1, c=m[r][j-s][0], d=m[r][j-s][1]; if(op[r]=='+') { minf=a+c; maxf=b+d; } else { e[1]=a*c; e[2]=a*d; e[3]=b*c; e[4]=b*d; minf=e[1]; maxf=e[1]; for(int k=2; k<5; k++) { if(minf>e[k]) minf=e[k]; if(maxf<e[k]) maxf=e[k]; } } } int polyMax(){ for(int i=1;i<=n;i++) for(int j=2;j<=n;j++){ m[i][j][0]=1000000; m[i][j][1]=-1000000; } for(int j=2; j<=n; j++) for(int i=1; i<=n; i++) for(int s=1; s<j; s++) { minMax(i,s,j); if(m[i][j][0]>minf) m[i][j][0]=minf; if(m[i][j][1]<maxf) m[i][j][1]=maxf; } int temp=m[1][n][1]; for(int i=2; i<=n;i++) if(temp<m[i][n][1]) temp=m[i][n][1]; return temp; } int main() { memset(m,0,sizeof(m)); cin >> n; getchar(); for(int i=1;i<=n;i++) { cin >> op[i] >> v[i]; getchar(); m[i][1][0]=m[i][1][1]=v[i]; } cout << polyMax() <<endl; return 0; }

5 May 2020, 14:37 | Views: 5297

Add new comment

For adding a comment, please log in
or create account

0 comments