HDU 2577 How to Type (dp)

本文介绍了一种解决特定字符串键盘输入最小按键数问题的算法。通过动态规划的方法,计算了给定字符串在考虑大小写切换的情况下,使用最少按键完成输入的方案。

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

 http://acm.hdu.edu.cn/showproblem.php?pid=2577

 

题意:给出一个包含大小写的字符串,问使用键盘打字至少需要按键多少下,可以使用shift 和caps lock 切换大小写。

 

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

 

解题思路:

动态规划,dp[110][2];//前i个字符,结果为(小写0,大写1)的最少按键数

根据当前字符的大小写推出公式。

 

 

#include <iostream>
#include <ctype.h>
using namespace std ;


int min(int a,int b)
{
	return a<b?a:b;
}
void main()
{
	int cass;
	cin>>cass;
	while(cass--)
	{
		char str[110];
		int dp[110][2];//前i个字符,结果为(小写0,大写1)的最少按键数
		scanf("%s",str+1);
		dp[0][0] = 0;//零个字符,按键为0次
		dp[0][1] = 1;//零个字符大写,按键为1次
		for(int i=1;str[i];i++)
		{
			if(islower(str[i]))//如果第i个字符是小写
			{
				dp[i][0] = min(dp[i-1][0]+1,dp[i-1][1]+2);
				dp[i][1] = min(dp[i-1][0]+2,dp[i-1][1]+2);
			}
			else//如果第i个字符是大写
			{
				dp[i][0] = min(dp[i-1][0]+2,dp[i-1][1]+2);
				dp[i][1] = min(dp[i-1][0]+2,dp[i-1][1]+1);
			}
		}
		printf("%d\n", min( dp[i-1][0] , dp[i-1][1]+1 ));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值