Http://uva.onlinejudge.org/external/105/10559.html
It is said that the black book has an explanation of the very good DP question.
After thinking for a long time, I knew this was the interval DP, but I didn't know what to maintain, so I had to find a solution. The problem that someone else wrote for this question is still clear. The main idea is to determine which color is used as the final color and whether the color is eliminated. If the number of blocks in the remaining colors is eliminated, the number of blocks that are not eliminated is 0. Otherwise, the number of blocks that were not eliminated last time is added to continue the DP process.
Set a three-dimensional state. DP [I] [J] [k] indicates that the State is not eliminated in the range [I, j, the number of blocks with the same color and position J. Then, each DP transfer is performed to determine whether the last block, together with the previous one, is eliminated. The main one here is why no other colors need to be recorded. The reason is that if you want to remove the last block of blocks in the same color together with other blocks in the same color, the remaining blocks in other colors are not allowed in the middle. This explains why only one color block needs to be recorded.
The Code is as follows:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 typedef vector<int> Array; 5 const int N = 222; 6 Array clr, cnt, a; 7 int dp[N][N][N]; 8 9 inline void Update(int &a, const int b) {10 a = max(b, a);11 }12 13 int Gao(int m) {14 //for (int i = 0; i < m; ++i) { cout << clr[i] << ‘ ‘ << cnt[i] << endl; }15 for (int i = 0; i < m; ++i) {16 for (int j = 0; j < m; ++j) {17 for (int k = 0; k < N; ++k) {18 if (i > j && k == 0) {19 dp[i][j][k] = 0;20 } else {21 dp[i][j][k] = -1;22 }23 }24 }25 }26 for (int d = 1; d <= m; ++d) {27 for (int l = 0; l + d <= m; ++l) {28 int r = l + d - 1;29 Update(dp[l][r][0], dp[l][r - 1][0] + cnt[r] * cnt[r]);30 Update(dp[l][r][cnt[r]], dp[l][r - 1][0]);31 for (int t = l; t < r; ++t) {32 if (clr[t] == clr[r]) {33 for (int k = 0; k + cnt[r] < N; ++k) {34 if (dp[l][t][k] >= 0) {35 Update(dp[l][r][k + cnt[r]], dp[l][t][k] + dp[t + 1][r - 1][0]);36 Update(dp[l][r][0], dp[l][t][k] + dp[t + 1][r - 1][0] + (k + cnt[r]) * (k + cnt[r]));37 }38 }39 }40 }41 }42 }43 //for (int i = 0; i < m; ++i) { cout << dp[i][i][1] << endl; }44 return dp[0][m - 1][0];45 }46 47 int Run() {48 int T, n;49 cin >> T;50 for (int cas = 1; cas <= T; ++cas) {51 cin >> n;52 a.resize(n);53 for (int i = 0; i < n; ++i) {54 cin >> a[i];55 }56 clr.clear();57 cnt.clear();58 for (int i = 0; i < n; ) {59 int j = i;60 while (j < n && a[i] == a[j]) {61 ++j;62 }63 clr.push_back(a[i]);64 cnt.push_back(j - i);65 i = j;66 }67 cout << "Case " << cas << ": " << Gao(clr.size()) << endl;68 }69 return 0;70 }71 72 int main() {73 //freopen("in", "r", stdin);74 ios::sync_with_stdio(0);75 return Run();76 }
View code
-- Written by lyonlys
Ultraviolet A 10559 Blocks