感觉这道dp题还是有点技巧的,此题设置了两个数组:open[]和close[],分别用来记录capslock一直开启状态和一直关闭状态下的最少输入次数。此时只要判断字母的大小写,选用最优子结构即可。状态转移方程为:
str[i]是小写字母:
open[i]=min(open[i-1]+2,close[i-1]+2);
close[i]=min(close[i-1]+1,open[i-1]+2);
str[i]是大写字母:
open[i]=min(open[i-1]+1,close[i-1]+2);
close[i]=min(close[i-1]+2,open[i-1]+2);
#include"iostream" #include"stdio.h" #include"string.h" #include"ctype.h" #define mx 1000 using namespace std; char str[mx]; int open[mx],close[mx]; int min(int a,int b) { return a<b?a:b; } int main() { int i,j,t; cin>>t; getchar(); while(t--) { memset(open,0,sizeof(open)); memset(close,0,sizeof(close)); cin>>str; if(islower(str[0])) {open[0]=2;close[0]=1;} else {open[0]=2;close[0]=2;} for(i=1;str[i]!=‘\0‘;i++) { if(islower(str[i])) { open[i]=min(open[i-1]+2,close[i-1]+2); close[i]=min(close[i-1]+1,open[i-1]+2); } else { open[i]=min(open[i-1]+1,close[i-1]+2); close[i]=min(close[i-1]+2,open[i-1]+2); } } cout<<close[i-1]<<endl; } return 0; }
时间: 2024-11-05 06:27:06