Educational Codeforces Round 61 (Rated for Div. 2) F. Clear the String(区间DP)
原创
©著作权归作者所有:来自51CTO博客作者wx5e9d3f1cab2eb的原创作品,请联系作者获取转载授权,否则将追究法律责任
F. Clear the String
题意:给出一个串,每次消去连续相同的子串,问最少多少次能把这个串消完。
题解:入门区间
。两种做法。
- 做法一:记忆化
- 。首先肯定可以知道对于 一段区间
- ,它只有两种情况,里面的字符全部相同,或者分成若干段相同区间。那么我们就可以暴力枚举区间里的中点,累加每段的区间贡献即可。对于每段区间里的字符,只要它和区间两端点字符不相同,那么它就需要消掉,即次数加一。
- 做法二:直接
- 。
- 表示将区间
- 消完所需要的最少次数。那么,如果
- ,那么很明显区间
- ,因为中间的
- 是已经消完了的,而
- ,因此只需要再加一次即可。否则就判断一下是消去
- 更优还是消去
- 更优。不过要注意有可能区间
- 里有可能还有和区间端点相同的,因此我们要枚举一下,然后取
- 即可
代码
#include<bits/stdc++.h>
#define DEBUG(x) std::cerr << #x << '=' << x << std::endl
using namespace std;
int dp[600][600],n;
string s;
int dfs(int l,int r)
{
if(r < l) return 0;
if(dp[l][r] != - 1) return dp[l][r];
int min1 = INT_MAX;
for(int i = l; i <= r; ++i) {
int ret = dfs(l, i - 1) + dfs(i + 1, r);
if(s[i] != s[l - 1] && s[i] != s[r + 1]) ret++;
min1 = min(min1, ret);
}
return dp[l][r] = min1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in","r",stdin);
#endif
ios::sync_with_stdio(false); cin.tie(0);
memset(dp, -1, sizeof dp);
cin >> n >> s;
s = '\0' + s + '\0';
cout << dfs(1,n) << endl;
return 0;
}
- 区间
#include<bits/stdc++.h>
#define DEBUG(x) std::cerr << #x << '=' << x << std::endl
using namespace std;
const int N = 555;
int dp[N][N];
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.in","r",stdin);
#endif
ios::sync_with_stdio(false); cin.tie(0);
int n;
string s;
cin >> n >> s;
s = '\0' + s;
for(int i = 1; i <= n; ++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(s[i] == s[j]) dp[i][j] = dp[i + 1][j - 1] + 1;
else dp[i][j] = min(dp[i + 1][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][j] - 1);
}
}
}
cout << dp[1][n] << endl;
return 0;
}