Problem Description
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
Sample Output
8
8
8
<div style='font-family:Times New Roman;font-size:14px;background-color:F4FBFF;border:#B7CBFF 1px dashed;padding:6px'><div style='font-family:Arial;font-weight:bold;color:#7CA9ED;border-bottom:#B7CBFF 1px dashed'><i>Hint</i></div>
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
</div>
这题比较经典,它是由两个不同的状态相互推导得到状态转移方程,用两个数组记录打印第i个字母时Caps Lock的状态,a表示灯开,b表示灯灭,则
如果第i个字母是小写:a[i]=min(a[i-1]+2,b[i-1]+2) //开:按shift+字母 关:按字母再开灯
b[i]=min(a[i-1]+2,b[i-1]+1) //开:关灯再按字母 关:直接按字母
如果第i个字母是大写:a[i]=min(a[i-1]+1,b[i-1]+2) //开:直接按字母 关:开灯再按字母
b[i]=min(a[i-1]+2,b[i-1]+2) //开:按字母再关灯 关:按shift+字母
因为最后Caps Lock是关的,a[n]要加一。
代码:
#include<stdio.h>
#include<string.h>
int a[105],b[105];
char str[105];
int min(int a,int b)
{
if(a<b)
return a;
return b;
}
int main()
{
int n,m,i,j;
scanf("%d",&n);
while(n--)
{
scanf("%s",str+1); //这里要注意,下标从一开始
m=strlen(str+1);
memset(a,0,sizeof(a));
a[0]=1;
for(i=1;i<=m;i++)
{
if(str[i]>='a'&&str[i]<='z')
{
a[i]=min(a[i-1]+2,b[i-1]+2);
b[i]=min(a[i-1]+2,b[i-1]+1);
}
else
{
a[i]=min(a[i-1]+1,b[i-1]+2);
b[i]=min(a[i-1]+2,b[i-1]+2);
}
}
a[m]++;
int answer=min(a[m],b[m]);
printf("%d\n",answer);
}
return 0;
}