HDU 2476 String painter(区间DP+思维)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2476

题目大意:给你字符串A、B,每次操作可以将一段区间刷成任意字符,问最少需要几次操作可以使得字符串A等于B。
解题思路:

先计算出将空串刷成字符串B的最小操作数,再去计算将A串刷成B串的最小操作数。

设dp[i][j]表示将空串[i,j]刷成跟B串一样的最小操作次数,所以得到状态转移方程:

dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]),(i<=k<j)
if(_str[i]==_str[j])
  dp[i][j]--;

这里跟LightOJ 1422 写法差不多。

接下来设ans[i]表示将字符串A的[0,i]刷成B的最小操作次数,得到状态转移方程:

ans[i]=min(ans[i],ans[j]+dp[j+1][i]),(0<=j<i)

代码

 1 #include<cstdio>
 2 #include<cmath>
 3 #include<cctype>
 4 #include<cstring>
 5 #include<iostream>
 6 #include<algorithm>
 7 #include<vector>
 8 #include<queue>
 9 #include<set>
10 #include<map>
11 #include<stack>
12 #include<string>
13 #define lc(a) (a<<1)
14 #define rc(a) (a<<1|1)
15 #define MID(a,b) ((a+b)>>1)
16 #define fin(name)  freopen(name,"r",stdin)
17 #define fout(name) freopen(name,"w",stdout)
18 #define clr(arr,val) memset(arr,val,sizeof(arr))
19 #define _for(i,start,end) for(int i=start;i<=end;i++)
20 #define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
21 using namespace std;
22 typedef long long LL;
23 const int N=5e2+5;
24 const int INF=0x3f3f3f3f;
25 const double eps=1e-10;
26 
27 int ans[N],dp[N][N];
28 char str[N],_str[N];
29 
30 int main(){
31     while(~scanf("%s",str)){
32         scanf("%s",_str);
33         int n=strlen(str);
34         for(int i=0;i<n;i++){
35             dp[i][i]=1;
36         }
37         //写法跟lightoj 1422 那个换装类似
38         for(int len=1;len<n;len++){
39             for(int i=0;i+len<n;i++){
40                 int j=i+len;
41                 dp[i][j]=dp[i][j-1]+1;
42                 for(int k=i;k<=j;k++){
43                     dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
44                 }
45                 if(_str[i]==_str[j])
46                     dp[i][j]--;
47             }
48         }
49         for(int i=0;i<n;i++){
50            ans[i]=dp[0][i];
51            if(str[i]==_str[i]){
52                 if(i==0) ans[0]=0;
53                 else ans[i]=ans[i-1];
54            }
55            for(int j=0;j<i;j++)
56             ans[i]=min(ans[i],ans[j]+dp[j+1][i]);
57         }
58         printf("%d
",ans[n-1]);
59     }
60     return 0;
61 }
原文地址:https://www.cnblogs.com/fu3638/p/8861053.html