@xunuo
2017-03-24T19:26:59.000000Z
字数 2353
阅读 1162
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
贪心
动态规划(DP)
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.
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.
For each test case, you must output the smallest times of typing the key to finish typing this string.
3
Pirates
HDUacm
HDUACM
8
8
8
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
题意:
Pirates敲键盘,只有大写字母和小写字母组成的字符串,大小写转换时只可以使用caps键和shift键;问你输入该字符串时,最少要按多少次键盘;
解题思路:
我是用的贪心写,但是学长讲的时候是用的DP;
但是自己写贪心的时候少了一种情况:当有如AAiA这种情况,i就可以通过按shift键来打出i;而不是将caps熄灭再按;
完整代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char s[110];
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
scanf("%s",s);
int l=strlen(s);
int sum=l;
// printf("%d\n",sum);
int flag=0;
for(int i=0;i<l;i++)
{
if(s[i]>='A'&&s[i]<='Z'&&flag==0)
{
if((s[i+1]>='a'&&s[i+1]<='z')||(i==l-1))
sum++;///shift
else
{
sum++;///caps亮
flag=1;
}
}
else if(((s[i]>='a'&&s[i]<='z')||i==l-1)&&flag==1)
{
if((i!=l-1)&&s[i+1]>='A'&&s[i+1]<='Z')
sum++;
else
{
sum++;
flag=0;
}
}
}
printf("%d\n",sum);
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int dp[110][2];///dp[i][0]表示在第i个字母时caps键没亮,dp[i][1]表示在第i个字母时caps键亮;
char s[110];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(dp,0,sizeof(dp));
scanf("%s",s);
int l=strlen(s);
if(s[0]>='A'&&s[0]<='Z')
{
dp[0][0]=2;
dp[0][1]=2;
}
else if(s[0]>='a'&&s[0]<='z')
{
dp[0][0]=1;
dp[0][1]=2;
}
for(int i=1;i<l;i++)
{
if(s[i]>='A'&&s[i]<='Z')
{
dp[i][0]=min(dp[i-1][0]+2/*前面caps键没亮,按shift+该字母或caps+该字母*/,dp[i-1][1]+2/*当前灯亮了,先按了该字母,再将caps键灭掉*/);
dp[i][1]=min(dp[i-1][0]+2/*前面caps键没亮,按caps键后再按该字母*/,dp[i-1][1]+1/*当前灯亮了,按了该字母,不用按caps键*/);
}
else if(s[i]>='a'&&s[i]<='z')
{
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);
}
}
printf("%d\n",dp[l-1][0]);
}
return 0;
}