hdu 2577:How to Type(动态规划)
http://acm.hdu.edu.cn/showproblem.php?pid=2577
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
题意分析:
给出一行有大小写的字符串,求最少的按键次数,小写字母可以在不开锁定状态下用Shift键加字母输入,大写字母同理,如果在输入结束后大写锁定是开的必须要关掉。
解题思路:
dp[i][0]代表在第i个字母,大写锁定关闭。
dp[i][1]代表在第i个字母,大写锁定开启。
当第i个字母是大写的时候:
1.开锁定
如果前一个字母开了锁定,只要按键1次;如果没开,则需要开锁定+按键,2次。
dp[i][1]=min(dp[i-1][1]+1, dp[i-1][0]+2);
2.不开锁定
如果前一个字母开了锁定,按字母+关锁定,2次;如果没开,Shift+字母,2次。
dp[i][0]=min(dp[i-1][1]+2, dp[i-1][0]+2);
当第i个字母是小写的时候:
1.开锁定
如果前一个字母开了锁定,Shift+字母,2次;如果没开,则需要按键+开锁定,2次。
dp[i][1]=min(dp[i-1][1]+2, dp[i-1][0]+2);
2.不开锁定
如果前一个字母开了锁定,关锁定+按字母,2次;如果没开,按字母,1次。
dp[i][0]=min(dp[i-1][1]+2, dp[i-1][0]+1);
最后输出dp[n][0], 和dp[n][1]+1(关锁定要1步)中较小的一个。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define N 120
using namespace std;
int dp[N][2];
char str[N];
int main()
{
int t, n, i;
scanf("%d", &t);
while(t--)
{
scanf("%s", str+1);
memset(dp, 0, sizeof(dp));
dp[0][1]=1;
n=strlen(str+1);
for(i=1; i<=n; i++)
{
if(str[i]>='A' && str[i]<='Z')
{
dp[i][1]=min(dp[i-1][1]+1, dp[i-1][0]+2);
dp[i][0]=min(dp[i-1][1]+2, dp[i-1][0]+2);
}
else
{
dp[i][1]=min(dp[i-1][1]+2, dp[i-1][0]+2);
dp[i][0]=min(dp[i-1][1]+2, dp[i-1][0]+1);
}
}
printf("%d\n", dp[n][0], dp[n][1]+1);
}
return 0;
}