hdu 2577 How to Type(DP)

本文介绍了一种算法,用于计算给定字符串(包含大小写字母)在确保大写灯最终关闭的情况下,最少需要按键盘上的键多少次才能完成输入。

题意:

给一个字符串(有大写有小写),问最少需要按多少次【键盘上的键】才能写出来。

开始前大写灯是关着的。结束后也必须保证大写灯是关的。

例:

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

 

思路:

每打完一个字母大写灯都可能有两种状态。层次结构还是比较易看出来的。

dp[i][0]:打完第i个字母大写灯是关闭状态所花最少次数。

dp[i][1]:打完第i个字母大写灯是开启状态所花最少次数。

 

代码:

int dp_closed[105];
int dp_open[105];


int main(){

    int T;
    char str[105];

    cin>>T;
    while(T--){
        scanf("%s",str);
        int L=strlen(str);

        dp_open[0]=1;
        dp_closed[0]=0;
        rep(i,1,L-1){
            if(str[i-1]>='a' && str[i-1]<='z'){
                dp_closed[i]=min( dp_closed[i-1]+1,dp_open[i-1]+2 );
                dp_open[i]=min( dp_closed[i-1]+2,dp_open[i-1]+2 );
            }else{
                dp_closed[i]=min( dp_closed[i-1]+2,dp_open[i-1]+2 );
                dp_open[i]=min( dp_closed[i-1]+2,dp_open[i-1]+1 );
            }
        }
        if(str[L-1]>='a' && str[L-1]<='z'){
            dp_closed[L]=min( dp_open[L-1]+2,dp_closed[L-1]+1 );
        }else{
            dp_closed[L]=min( dp_open[L-1]+2,dp_closed[L-1]+2 );
        }
        printf("%d\n",dp_closed[L]);
    }

    return 0;
}

 

转载于:https://www.cnblogs.com/fish7/p/4330780.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值