B - Halloween Costumes(区间dp)

在这里插入图片描述

Input

Input starts with an integer T (≤ 200), denoting the number of test cases.

Each case starts with a line containing an integer N (1 ≤ N ≤ 100) denoting the number of parties. Next line contains N integers, where the i t h i^{th} ith integer c i c_i ci (1 ≤ c i c_i ci ≤ 100) denotes the costume he will be wearing in party i. He will attend party 1 first, then party 2, and so on.

Output

For each case, print the case number and the minimum number of required costumes.

Sample Input

2
4
1 2 1 2
7
1 2 1 1 3 2 1

Sample Output

Case 1: 3
Case 2: 4

莫名其妙就过了的一道题
dp[i][j]表示参加派对i到派对j需要的最少的衣服件数。当区间长度为1时,衣服一定为1,所以初始化dp[i][i]=1。
每次只判断区间的头元素和尾元素否相同,如果相同,就等于dp[i][j-1],如果不同,就等于dp[i][j-1]+1。

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;

int arr[105];
int dp[105][105];

int main(void)
{
	int t,n,id=1;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
			scanf("%d",&arr[i]);
		memset(dp,0,sizeof dp);
		for(int i=1;i<=n;i++)
			dp[i][i]=1;
		for(int len=2;len<=n;len++)
			for(int i=1;i<=n-len+1;i++)
			{
				int j=i+len-1;
				dp[i][j]=INF;
				if(arr[i]==arr[j])
					dp[i][j]=dp[i][j-1];
				else
					dp[i][j]=dp[i][j-1]+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",id++,dp[1][n]);
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值