hdu 6212 區間dp
阿新 • • 發佈:2018-12-01
題意:祖瑪遊戲,最少的彈藥消除所有珠子
思路:區間dp,注意列舉中間空一個珠子的情況,這裡要注意的是中間不能有兩個,並且兩邊的加中間列舉的也不能是三個(因為這樣不管先取左右都會直接被消除掉)
程式碼:
#include<bits/stdc++.h> using namespace std; struct node { int num, color; }ball[515]; int f[515][515]; int a[515], m, n; char input[500]; int main(){ int t; scanf("%d", &t); int caset = 0; while (t--){ scanf("%s", input); n = strlen(input); for (int i = 1; i <= n; i++)a[i] = input[i - 1] - '0'; int bal = a[1], num = 0; m = 0; for (int i = 1; i <= n; i++){ if (a[i] != bal) { ball[++m].num = num; ball[m].color = bal; num = 1; bal = a[i]; } else num++; } ball[++m].num = num; ball[m].color = bal; for (int i = 1; i <= m; i++) if (ball[i].num > 1)f[i][i] = 1; else f[i][i] = 2; for (int p = 2; p <= m; p++){ for (int i = 1; i + p - 1 <= m; i++){ int j = i + p - 1; f[i][j]=1e9; if (ball[i].color == ball[j].color){ if (ball[i].num + ball[j].num == 2) f[i][j] = f[i + 1][j - 1] + 1; else f[i][j] = f[i + 1][j - 1]; for (int k = i + 2; k<j - 1; k++) if (ball[k].color == ball[i].color&&ball[k].num==1&&(ball[i].num==1||ball[j].num==1)) f[i][j] = min(f[i][j], f[i+1][k-1]+f[k+1][j-1]); } for (int k = i; k<j; k++) f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j]); } } printf("Case #%d: %d\n", ++caset, f[1][m]); } return 0; }