USACO 2020~2021 February Contest GOLD 题解(2)

USACO 2020~2021 二月黄金组 题解(2)

2. Modern Art 3

Having become bored with standard 2-dimensional artwork (and also frustrated at others copying her work), the great bovine artist Picowso has decided to switch to a more minimalist, 1-dimensional style. Her latest painting can be described by a 1-dimensional array of colors of length N (1≤N≤300), where each color is specified by an integer in the range 1…N.
To Picowso’s great dismay, her competitor Moonet seems to have figured out how to copy even these 1-dimensional paintings! Moonet will paint a single interval with a single color, wait for it to dry, then paint another interval, and so on. Moonet can use each of the N colors as many times as she likes (possibly none).
Please compute the number of such brush strokes needed for Moonet to copy Picowso’s latest 1-dimensional painting.

题目大意:Picowso要给一个长度为N的一维画板染色(1<=N<=300), 其中第i个位置需要染成ci的颜色。他每次可以将任意一个区间染成同一种颜色。计算达成目标染色方案所需的最少染色次数。

题目分析:可以说是相当经典的区间dp问题了。由于N的范围很小,我们不需要任何优化便可以轻松通过本题。 考虑状态转移方程,设染色区间[i,j]所需最少染色次数为dp(i,j)。我们发现,区间第一个和最后一个端点在可以在一开始就染色,因为中间的端点染色不会影响到它们的颜色。因此,如果左右端点颜色相同,右端点不需要额外多染色一次,因为第一次染色就可以把左右一起染色。那么:
d p ( i , j ) = { d p ( i , j − 1 ) c i  =  c j m i n ( d p ( i , k ) + d p ( k + 1 , j ) ) c i   ≠   c j dp(i,j)=\begin{cases} dp(i,j-1)& \text{$c_i$ = $c_j$}\\ min(dp(i,k)+dp(k+1,j))& \text{$c_i$ $\not=$ $c_j$} \end{cases} dp(i,j)={dp(i,j1)min(dp(i,k)+dp(k+1,j))ci = cjci = cj
这个算法是O(n3)的。

代码如下:

#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N=305;
int n,dp[N][N],a[N];
int main(){
    scanf("%d",&n);
    memset(dp,0x3f,sizeof dp);//别忘了初始化
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        dp[i][i]=1;
    }
    for(int len=2;len<=n;len++)
    {
        for(int i=1;i+len-1<=n;i++)
        {
            int j=i+len-1;
            if(a[i]==a[j])dp[i][j]=dp[i][j-1];
            else for(int k=i;k<j;k++)dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
        }
    }
    printf("%d",dp[1][n]);
}

第二题比第一题更为容易,其实算作签到题也不为过。本次黄金组表现如何还得看第三题。本次比赛其余题目将在之后陆续更新~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值