转眼间已经到DP模块了。。。。
How to Type
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1781 Accepted Submission(s): 837
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
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
自己做了好久没有找到状态转移方程,开了别人的解题报告才知道,,惭愧。。。
on[i] 表示在输入第i个字符后 Caplock 灯是亮着的,off[i]表示在输入第i个字符后Caplock灯是熄的。 (注意是,输入字符后!)
所以有状态方程:
当第i个字符是大写时 on[i]=min(on[i-1]+1,off[i-1]+2),off[i]=min(on[i-1]+2,off[i-1]+2)
当第i个字符是小写时 off[i]=min(on[i-1]+2,off[i-1]+2),off[i]=min(on[i-1]+2,off[i-1]+1)
同时注意初始状态: 如果第一个字符为大写: on[0]=2 先Caplock 再输入
off[0]=2 先输入再Caplock
如果第一个字符是小写: on[0]=2 先输入在Caplock
off[0]=1 直接输入
代码:
View Code
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <algorithm> 5 using namespace std; 6 7 8 bool Is_up(char a) 9 { 10 if(a>='A' && a<='Z') 11 return true; 12 else return false; 13 } 14 15 16 int main() 17 { 18 int t; 19 int i,j; 20 scanf("%d",&t); 21 while(t--) 22 { 23 int on[110],off[110]; 24 char str[110]; 25 scanf("%s",str); 26 int len=strlen(str); 27 if(Is_up(str[0])) 28 { 29 on[0]=2; 30 off[0]=2; 31 } 32 else 33 { 34 on[0]=2; 35 off[0]=1; 36 } 37 for(i=1;i<len;i++) 38 { 39 if(Is_up(str[i])) 40 { 41 on[i]=min(on[i-1]+1,off[i-1]+2); 42 off[i]=min(on[i-1]+2,off[i-1]+2); 43 } 44 else 45 { 46 on[i]=min(on[i-1]+2,off[i-1]+2); 47 off[i]=min(on[i-1]+2,off[i-1]+1); 48 } 49 } 50 on[len-1]++; 51 52 cout<<min(on[i-1],off[i-1])<<endl; 53 } 54 return 0; 55 }