区间DPB. Zuma
Posted 行码棋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了区间DPB. Zuma相关的知识,希望对你有一定的参考价值。
https://codeforces.com/problemset/problem/607/B
f [ i ] [ j ] f[i][j] f[i][j]:代表区间 [ i , j ] [i,j] [i,j]合并的最小花费
- 初始化:
f [ i ] [ i ] = 1 f[i][i] = 1 f[i][i]=1
f [ i ] [ i + 1 ] = 1 , a [ i ] = = a [ i + 1 ] f[i][i + 1] = 1, a[i]==a[i + 1] f[i][i+1]=1,a[i]==a[i+1]
f [ i ] [ i + 1 ] = 2 , a [ i ] ≠ a [ i + 1 ] f[i][i +1] = 2, a[i] \\neq a[i + 1] f[i][i+1]=2,a[i]=a[i+1] - 转移方程:
f [ i ] [ j ] = f [ i + 1 ] [ j − 1 ] , a [ i ] = = a [ j ] f[i][j] = f[i + 1][j - 1], a[i] == a[j] f[i][j]=f[i+1][j−1],a[i]==a[j]
f [ i ] [ j ] = m i n ( f [ i ] [ k ] + f [ k + 1 ] [ j ] ) , i ≤ k < j f[i][j] = min(f[i][k] + f[k + 1][j]), i \\leq k \\lt j f[i][j]=min(f[i][k]+f[k+1][j]),i≤k<j
区间DP一般都是由两个小的区间合并成一个大的区间,所以第三维循环非常常见,应该对此非常敏感
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 505, mod = 19650827;
int f[N][N], a[N];
int main()
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i];
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
f[i][j] = 0x3f3f3f3f;
for(int i = 1; i <= n; i++)
f[i][i] = 1;
if(i < n) f[i][i + 1] = 1 + (a[i] != a[i + 1]);
for(int len = 3; len <= n; len ++)
for(int i = 1; i + len - 1 <= n; i++)
int j = i + len - 1;
if(a[i] == a[j])
f[i][j] = f[i + 1][j - 1];
for(int k = i; k < j; k++)
f[i][j] = min(f[i][j], f[i][k] + f[k + 1][j]);
cout << f[1][n] << "\\n";
return 0;
以上是关于区间DPB. Zuma的主要内容,如果未能解决你的问题,请参考以下文章
[BZOJ1032][JSOI2007]祖码Zuma 区间dp