[POJ 1179] Polygon【区间DP】
Problem:
Time Limit: 1000MS | Memory Limit: 10000K |
Description

�pick an edge E and the two vertices V1 and V2 that are linked by E; and
�replace them by a new vertex, labelled with the result of performing the operation indicated in E on the labels of V1 and V2.
The game ends when there are no more edges, and its score is the label of the single vertex remaining.Consider the polygon of Figure 1. The player started by removing edge 3. After that, the player picked edge 1, then edge 4, and, finally, edge 2. The score is 0.

Input
3 <= N <= 50
For any sequence of moves, vertex labels are in the range [-32768,32767].
Output
Sample Input
4 t -7 t 4 x 2 x 5
Sample Output
33 1 2
Source
Solution:
本来是要练四边形不等式优化来着。。找了道和“石子归并”差不多的题,结果竟然用不了。。
这道题是石子归并的升级版,操作变成了 + 和 * 两种。
直接拆环成链,用区间 DP 套就可以了。。
唯一坑点是由于负数的存在,最大值还可能由 2 个最小值或 1 个最大值和 1 个最小值相乘而得。
所以最小值也要记录。1A ~~~
Code: O(N3)
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> #include<algorithm> using namespace std; inline char getop(){ char ch; while((ch = getchar()) != EOF && ch != 't' && ch != 'x'); return ch; } int N, v[110]; bool op[110]; int u[110][110], l[110][110]; int main(){ scanf("%d", &N); for(register int i = 1; i <= N; i++){ op[i + N] = op[i] = (getop() == 't') ? 0 : 1; scanf("%d", v + i), v[i + N] = v[i]; } memset(u, 0xc0, sizeof(u)), memset(l, 0x3f, sizeof(l)); for(register int i = 1; i < (N << 1); i++) u[i][i] = l[i][i] = v[i]; for(register int gp = 1; gp < N; gp++) for(register int i = 1; i < (N << 1) - gp; i++){ int j = i + gp; for(register int k = i; k < j; k++){ if(op[k + 1]){ u[i][j] = max(u[i][j], max(u[i][k] * u[k + 1][j], max(u[i][k] * l[k + 1][j], max(l[i][k] * u[k + 1][j], l[i][k] * l[k + 1][j])))); l[i][j] = min(l[i][j], min(u[i][k] * u[k + 1][j], min(u[i][k] * l[k + 1][j], min(l[i][k] * u[k + 1][j], l[i][k] * l[k + 1][j])))); } else{ u[i][j] = max(u[i][j], u[i][k] + u[k + 1][j]); l[i][j] = min(l[i][j], l[i][k] + l[k + 1][j]); } } } int maxv = 0xc0c0c0c0; for(register int i = 1; i <= N; i++) maxv = max(maxv, u[i][i + N - 1]); printf("%d\n", maxv); bool isfirst = 1; for(register int i = 1; i <= N; i++) if(u[i][i + N - 1] == maxv){ if(!isfirst) printf(" %d", i); else isfirst = 0, printf("%d", i); } return 0; }
发表评论