Pirates have finished developing the typing software. He called Cathy to test his typing software. She is good at thinking. After testing for several days, she finds that if she types a string by some ways, she will type the key at least. But she has a bad habit that if the caps lock is on, she must turn off it, after she finishes typing. Now she wants to know the smallest times of typing the key to finish typing a string.
Input
The first line is an integer t (t<=100), which is the number of test case in the input file. For each test case, there is only one string which consists of lowercase letter and upper case letter. The length of the string is at most 100.
Output
For each test case, you must output the smallest times of typing the key to finish typing this string.
Sample Input
3
Pirates
HDUacm
HDUACM
Sample Output
8
8
8
Hint
The string “Pirates”, can type this way, Shift, p, i, r, a, t, e, s, the answer is 8.
The string “HDUacm”, can type this way, Caps lock, h, d, u, Caps lock, a, c, m, the answer is 8
The string "HDUACM", can type this way Caps lock h, d, u, a, c, m, Caps lock, the answer is 8
题意:我们要找键入字符串最小的按键次数。Cap有开关两种状态,0代表关,1代表开是常用的选择。关键是找出递推关系式!
我们由上一步状态来推该步状态的同时,应该确保上一步经过一系列操作后得到的Cap灯与该步的Cap灯同等状态!!!
#include<iostream>
#include<cstring>
using namespace std;
int dp[2][111];
int main()
{
char s[111];
int n;
cin>>n;
while(n--)
{
cin>>(s+1);//注意这里要向后移一位,以为dp做准备
int len=strlen(s);
memset(dp,0,sizeof(dp));
dp[0][0]=0;
dp[1][0]=1;
for(int i=1;i<len;i++)//从字符串的第一个起就开始遍历
{
if(s[i]>='A'&&s[i]<='Z')
{
dp[0][i]=min(dp[0][i-1]+2,dp[1][i-1]+2);//shift加打字,打字加关闭Cap
dp[1][i]=min(dp[0][i-1]+2,dp[1][i-1]+1);//开启Cap加打字,直接打字
}
else if(s[i]>='a'&&s[i]<='z')
{
dp[0][i]=min(dp[0][i-1]+1,dp[1][i-1]+2);//直接打字,关闭Cap加打字
dp[1][i]=min(dp[0][i-1]+2,dp[1][i-1]+2);//直接打字加开启Cap,shift加打字
}
}
cout<<min(dp[0][len-1],dp[1][len-1]+1)<<endl;//灯灭和灯亮+1的最小值,即灯亮时要关闭灯
}
return 0;
}