how to type题解

Pirates have finished developing the typing software. He called Cathyto 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

AC代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <cmath>
#include <string>
using namespace std;

int main()
{
    string a;
    int i,j,n,t,dpon[1001],dpoff[1001];
    cin>>t;
    while(t--){
        cin>>a;
        memset(dpon,0,sizeof(dpon));
        memset(dpoff,0,sizeof(dpoff));
        int ans=0;
        dpon[0]=1;
        n=a.size();
        ans+=n;
        for(i=0;i<n;i++){
            if(a[i]<='Z'&&a[i]>='A'){
                dpon[i+1]=min(dpon[i]+1,dpoff[i]+2);
                dpoff[i+1]=min(dpon[i]+2,dpoff[i]+2);
            }
            else{
                dpon[i+1]=min(dpon[i]+2,dpoff[i]+2);
                dpoff[i+1]=min(dpon[i]+2,dpoff[i]+1);

            }
        }
        dpon[n]++;
        printf("%d\n",min(dpon[n],dpoff[n]));
    }
    return 0;
}

核心部分

 for(i=0;i<n;i++){
                if(a[i]<='Z'&&a[i]>='A'){
                    dpon[i+1]=min(dpon[i]+1,dpoff[i]+2);//因为是大写,两种方式,一种是已经caps,所以只需在其基础上+1,二是小写,shift+1
                    dpoff[i+1]=min(dpon[i]+2,dpoff[i]+2);//小写锁可选择shift+1或者开启大写+1
                }
                else{
                    dpon[i+1]=min(dpon[i]+2,dpoff[i]+2);//道理同上
                    dpoff[i+1]=min(dpon[i]+2,dpoff[i]+1);
    
                }
            }

刚开始接触dp,这道应该算是简单的例题吧(大佬如是说)、、、

猜你喜欢

转载自blog.csdn.net/qq_43141958/article/details/88774941
今日推荐