这两天快被DP整崩溃啦!!!今天拿到这道题也是无从下手,问了下高手思路才做出来。
思路:
开另个数组on[], off[]。分别表示开Caps Lock灯,和关Caps Lock灯时的最小按键次数
当字符串s[i]为大写时:
on[i] = min{ on[i-1] + 1, off[i-1] + 2} //开灯时直接输入字母,关灯时按shift+字母;
off[i] = min{ on[i-1] + 2, off[i-1] + 2} //开灯时先输字母再关灯,关灯时按shift+字母;
当字符串s[i]为小写时:
on[i] = min{ on[i-1] + 2, off[i-1] + 2} //开灯时按shift+字母, 关灯时按字母再开灯;
off[i] = min{ on[i-1] + 2, off[i-1] + 1} //开灯时关灯再按键,关灯时直接按键;
My Code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 107;
int on[N], off[N];
char s[N];
int main()
{
//freopen("data.in", "r", stdin);
int t, len, i;
scanf("%d", &t);
while(t--)
{
scanf("%s", s);
memset(on, 0, sizeof(on));
memset(off, 0, sizeof(off));
on[0] = 1; len = strlen(s);
for(i = 1; i <= len; i++)
{
if(isupper(s[i-1]))
{
on[i] = min(on[i-1]+1, off[i-1]+2);
off[i] = min(off[i-1]+2, on[i-1]+2);
}
else
{
on[i] = min(off[i-1]+2, on[i-1]+2);
off[i] = min(off[i-1]+1, on[i-1]+2);
}
}
printf("%d\n", off[len]);
}
return 0;
}
。