D. Flood Fill(缩点+区间dp)

首先进行缩点,这样最终数组中最长的同色块长度为1;在套用区间dp的模板

状态转移方程

dp[l][r]=dp[l+1][r-1]+1 (a[l]\neq a[r])

dp[l][r]=min(dp[l][r-1],dp[l+1][r]) (a[l]= a[r])

ACcode

2022/7/15日更新一个缩点方法

vector<int>a; 
a.erase(unique(a.begin(), a.end()), a.end());

 

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int long long
#define endl '\n'
#define lowbit(x) x &(-x)
#define mh(x) memset(x, -1, sizeof h)
#define debug(x) cerr << #x << "=" << x << endl;
const int N = 2e2 + 10;
const int mod = 998244353;
const double esp = 1e-6;
const double pi = acos(-1);
typedef pair<int, int> PII;
signed main()
{
    cin.tie(0)->sync_with_stdio(0);
    int n;
    cin >> n;
    vector<int> a(n + 1);
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    a.erase(unique(a.begin(), a.end()), a.end());
    n = a.size() - 1;
    vector<vector<int>> dp((n + 1), vector<int>(n + 1));
    for (int len = 2; len <= n; len++)
    {
        for (int l = 1; l + len - 1 <= n; l++)
        {
            int r = l + len - 1;
            if (a[l] == a[r])
                dp[l][r] = dp[l + 1][r - 1] + 1;
            else
                dp[l][r] = min(dp[l + 1][r] + 1, dp[l][r - 1] + 1);
        }
    }
    cout << dp[1][n] << endl;
}

 

 ACcode

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 1e9 + 7, N = 1 << 13;
signed main()
{
    cin.tie(0)->sync_with_stdio(0);
    int n;
    cin >> n;
    vector<int> a{0};
    for (int i = 1; i <= n; i++)//读入时缩点
    {
        int x;
        cin >> x;
        if (a.back() != x)
        {
            a.push_back(x);
        }
    }
    n = a.size() - 1;
    vector<vector<int>> dp(n + 1, vector<int>(n + 1));
    for (int len = 2; len <= n; len++)
    {
        for (int l = 1; l + len - 1 <= n; l++)
        {
            int r = l + len - 1;
            if (a[l] == a[r])
            {
                dp[l][r] = dp[l + 1][r - 1] + 1;
            }
            else
            {
                dp[l][r] = min(dp[l + 1][r], dp[l][r - 1]) + 1;
            }
        }
    }
    cout << dp[1][n] << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值