1. 程式人生 > 其它 >POJ1390:方盒遊戲,考點:動態規劃變數設定

POJ1390:方盒遊戲,考點:動態規劃變數設定

原題:http://poj.org/problem?id=1390

描述

(由於百練上沒有這道題,但是這道題又很重要,我印象中老師講了好一會兒,所以還是寫一寫,題目描述直接照搬講義了)

問題分析

解法

程式碼如下:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 const int M = 210;
 6 struct Segment {
 7     int color;
 8
int len; 9 }; 10 Segment segments[M]; 11 int score[M][M][M]; 12 int ClickBox(int i, int j, int len) { 13 if (score[i][j][len] != -1) 14 return score[i][j][len]; 15 int result = (segments[j].len + len) * 16 (segments[j].len + len); 17 if (i == j) 18 return result;
19 result += ClickBox(i, j - 1, 0); 20 for (int k = i; k <= j - 1; ++k) { 21 if (segments[k].color != segments[j].color) 22 continue; 23 int r = ClickBox(k + 1, j - 1, 0); 24 r += ClickBox(i, k, segments[j].len + len); 25 result = max(result, r); 26
} 27 score[i][j][len] = result; 28 return result; 29 } 30 int main() 31 { 32 int T; 33 cin >> T; 34 for (int t = 1; t <= T; ++t) { 35 int n; 36 memset(score, 0xff, sizeof(score)); 37 cin >> n; 38 int lastC = 0; 39 int segNum = -1; 40 for (int i = 0; i < n; ++i) { 41 int c; 42 cin >> c; 43 if (c != lastC) { 44 segNum++; 45 segments[segNum].len = 1; 46 segments[segNum].color = c; 47 lastC = c; 48 } 49 else segments[segNum].len++; 50 } 51 cout << "Case " << t << ": " << ClickBox(0, segNum, 0) << endl; 52 } 53 return 0; 54 }