Hduoj2577【DP】

/*How to Type
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4656    Accepted Submission(s): 2108

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

Author
Dellenge

Source
HDU 2009-5 Programming Contest 

Recommend
lcy   |   We have carefully selected several similar problems for you:  2870 2830 2845 1058 1421 
*/
#include<stdio.h>
#include<string.h>
int min(int x, int y)
{
	return x<y?x:y;
}
int main()
{
	char str[110];
	int i, j, k, n, dp[101][2];
	scanf("%d", &n);
	while(n--)
	{
		scanf("%s", str);
		memset(dp, 0, sizeof(dp));
		k = strlen(str);
		dp[0][0] = 0;//off
		dp[0][1] = 10000000;//on
		for(i = 0; i < k; ++i)
		{
			if(str[i] >= 65 && str[i] <= 90)
			{
				dp[i+1][0] = min(dp[i][0] + 2, dp[i][1] + 2);
				dp[i+1][1] = min(dp[i][0] + 2, dp[i][1] + 1);
			} 
			else
			{
				dp[i+1][0] = min(dp[i][0] + 1, dp[i][1] + 2);
				dp[i+1][1] = min(dp[i][0] + 2, dp[i][1] + 2);
			}
		}
		printf("%d\n", min(dp[k][0], dp[k][1]+1) );
	}
	return 0;
} 


题意:给出一串字符串,求敲击键盘的 最小次数,刚开始大写键盘灯是关着的,其次最后键盘灯一定也要是关着的。敲击规则:敲击大写字母可以开启键盘灯敲写(当键盘灯是灭的)或者可以按shift键再敲字母(当键盘灯是灭的),或者直接敲字母(当键盘灯是亮的);小写字母也是一样的规则。

思路:这里说实话是很难想到用dp去做的,即分别保存第i个字母分别在键盘灯亮和灭时所需要的最小敲击次数,第i+1个字母的次数是前一个字母的基础上推算过来的,先讨论当前字母的大小写,再根据前一个字母分别在亮和灭时的次数求出当前字母在键盘灯亮和灭时所需要的最小次数。

你可能感兴趣的:(Hduoj2577【DP】)