hdu 2577:How to Type(动态规划)

本文介绍了一种算法,用于计算在考虑大写锁定状态的情况下,完成特定字符串输入所需的最少按键次数。通过动态规划方法,文章详细解释了如何根据不同字符(大写或小写)的状态,计算每一步的最佳按键方案,最终输出完成整个字符串输入所需的最小按键次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张宜强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值