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