题目链接:点击这里
题目大意:
小明要去参加
n
n
n 次宴会,每次宴会要求穿特定服装,小明身上的衣服可以套娃,脱掉的衣服不能再穿,求参加这
n
n
n 次宴会需要的最少衣服数量
题目分析:
区间
d
p
dp
dp
设
d
p
[
i
]
[
j
]
dp[i][j]
dp[i][j] 表示参加
i
i
i 到
j
j
j 宴会需要的最少衣服数量
初始时有
d
p
[
i
]
[
i
]
=
1
dp[i][i]=1
dp[i][i]=1
如果
a
[
i
]
=
a
[
j
]
a[i]=a[j]
a[i]=a[j] 显然有
d
p
[
i
]
[
j
]
=
d
p
[
i
]
[
j
−
1
]
dp[i][j]=dp[i][j-1]
dp[i][j]=dp[i][j−1] ,因为第
j
j
j 场可以用第
i
i
i 场的衣服
否则就正常枚举中间点转移:
d
p
[
i
]
[
j
]
=
m
i
n
(
d
p
[
i
]
[
k
]
+
d
p
[
k
+
1
]
[
j
]
)
,
(
i
≤
k
<
j
)
dp[i][j]=min(dp[i][k]+dp[k+1][j]),(i\le k<j)
dp[i][j]=min(dp[i][k]+dp[k+1][j]),(i≤k<j)
具体细节见代码:
//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
//#define int ll
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int read()
{
int res = 0,flag = 1;
char ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
{
res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
ch = getchar();
}
return res*flag;
}
const int maxn = 5e2+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
int n,a[maxn],dp[maxn][maxn];
int main()
{
int t = read();
for(int _ = 1;_ <= t;_++)
{
n = read();
memset(dp,0x3f,sizeof(dp));
for(int i = 1;i <= n;i++) a[i] = read(),dp[i][i] = 1;
for(int l = 2;l <= n;l++)
for(int i = 1,j = l;j <= n;i++,j++)
{
if(a[i] == a[j]) dp[i][j] = dp[i][j-1];
for(int k = i;k < j;k++) dp[i][j] = min(dp[i][j],dp[i][k]+dp[k+1][j]);
}
printf("Case %d: %d\n",_,dp[1][n]);
}
return 0;
}