HDU 2577 DP solution to a problem

HDU 2577 DP solution to a problem

2019-11-30

Written by WSY

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

2. Topic ideas: This question appears to be a string simulation, although I started is to do so , but the right way is DP. In everyone's cognition, the DP should be used to solve some similar stones merger, as the question of energy necklace, DP This question is how it will be used? ?

We assume dp [i] [0] represents the caps lock did not open now, dp [i] [1] represents the Caps Lock is now open, so you can launch such a recursive expression:

 

dp[i][1]=min(dp[i-1][1]+2,dp[i-1][0]+2);
dp[i][0]=min(dp[i-1][1]+2,dp[i-1][0]+1);

 

Oh, yes, before these words have to first determine the character is not upper / lower case:

bool checksmall(char a)
{
    if(a>='a'&&a<='z') return true;
    if(a>='A'&&a<='Z') return false;

}

So after such a code change is this pressure Son:

if(checksmall(a[i-1]))
{
    dp[i][1]=min(dp[i-1][1]+2,dp[i-1][0]+2); //1 capslock
    dp[i][0]=min(dp[i-1][1]+2,dp[i-1][0]+1);
}
else
{
    dp[i][1]=min(dp[i-1][1]+1,dp[i-1][0]+2);
    dp[i][0]=min(dp[i-1][1]+2,dp[i-1][0]+2);
}

Finally, give a welfare:

#include<bits/stdc++.h>
using namespace std;
bool checksmall(char a)
{
    if(a>='a'&&a<='z') return true;
    if(a>='A'&&a<='Z') return false;
}
int dp[100001][2];
int main()
{
    int n;
    char a[100001];
    scanf("%d",&n);
    while(n--)
    {
        memset(dp,0x3f,sizeof(dp));
        cin>>a;
        int l=strlen(a);
        dp[0][0]=0;
        dp[0][1]=1;
        for(int i=1;i<=l;i++)
        {
            if(checksmall(a[i-1]))
            {
                dp[i][1]=min(dp[i-1][1]+2,dp[i-1][0]+2); //1 capslock
                dp[i][0]=min(dp[i-1][1]+2,dp[i-1][0]+1);
            }
            else
            {
                dp[i][1]=min(dp[i-1][1]+1,dp[i-1][0]+2);
                dp[i][0]=min(dp[i-1][1]+2,dp[i-1][0]+2);
            }
        }
        //if(cpos==1) ans++;
        printf("%d\n",min(dp[l][0],dp[l][1]+1));
    }
    return 0;
}
Benefits: AC Code

thank you all!

 

 

Guess you like

Origin www.cnblogs.com/Moyra/p/11962511.html