传送门
题目描述
分析
还是区间DP的思路去写
f
[
i
]
[
j
]
f[i][j]
f[i][j]表示
[
i
,
j
]
[i,j]
[i,j]这个区间最少的涂色次数,我们去枚举区间
[
i
,
j
]
[i,j]
[i,j],分两种情况
- 如果 s t r [ i ] = = s t r [ j ] str[i] == str[j] str[i]==str[j],那么我只要在处理 [ i + 1 , j ] [i + 1,j] [i+1,j]或者 [ i , j − 1 ] [i,j - 1] [i,j−1]区间的时候多刷一格就可以了, f [ i ] [ j ] = m i n ( f [ i + 1 ] [ j ] , f [ i ] [ j − 1 ] ) f[i][j] = min(f[i + 1][j],f[i][j - 1]) f[i][j]=min(f[i+1][j],f[i][j−1])
- 如果 s t r [ i ] ! = s t r [ j ] str[i] != str[j] str[i]!=str[j],那么就去枚举临界点,两部分的值相加即可, f [ i ] [ j ] = m i n ( f [ i ] [ j ] , f [ i ] [ k ] + f [ k + 1 ] [ j ] ) f[i][j] = min(f[i][j],f[i][k] + f[k + 1][j]) f[i][j]=min(f[i][j],f[i][k]+f[k+1][j])
代码
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 100;
const ll mod= 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a){char c=getchar();T x=0,f=1;while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while(isdigit(c)){x=(x<<1)+(x<<3)+c-'0';c=getchar();}a=f*x;}
int gcd(int a,int b){return (b>0)?gcd(b,a%b):a;}
int f[N][N];
char str[N];
int n;
int main(){
scanf("%s",str + 1);
n = strlen(str + 1);
for(int i = 1;i <= n;i++) f[i][i] = 1;
for(int len = 2;len <= n;len++)
for(int i = 1,j = i + len - 1;j <= n;i++,j++){
f[i][j] = INF;
if(str[i] == str[j]) f[i][j] = min(f[i + 1][j],f[i][j - 1]);
else{
for(int k = i;k < j;k++) f[i][j] = min(f[i][j],f[i][k] + f[k + 1][j]);
}
}
di(f[1][n]);
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/