题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=2577
因为就一维DP表示前i个最小距离具有后效性,所以再开一维表示是否开了caps lock就好了
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cctype>
using namespace std;
const int maxn=100+5;
const int INF=0x3f3f3f3f;
const int O=1,C=0;
char str[maxn];
int d[maxn][2];
//d[i][j] 表示前i个字符 且有没有开caps lock的最小编辑距离
int main()
{
int T,i; cin>>T;
while(T--)
{
scanf("%s",str+1);
memset(d,INF,sizeof(INF));
d[0][C]=0; d[0][O]=1;
for(i=1;str[i];i++){
if(isupper(str[i])){ //Big letter
d[i][C]=min(d[i-1][O]+2,d[i-1][C]+2);
d[i][O]=min(d[i-1][O]+1,d[i-1][C]+2);
}
else {
d[i][C]=min(d[i-1][O]+2,d[i-1][C]+1);
d[i][O]=min(d[i-1][O]+2,d[i-1][C]+3);
}
}
cout<<min(d[i-1][O]+1,d[i-1][C])<<endl;
}
return 0;
}