http://acm.hdu.edu.cn/showproblem.php?pid=2577
此题为本人第一次自主分析动态规划。
对于每个字母之前的字母有两种状态 1.tab开启 2.tab没有开启,有数组分别记录两种状态下的最短时间,接下来状态转移方程:
0代表没开,1代表开了,对当前字母分类
小写字母: timer[i+1][0]=min(timer[i][0]+1,timer[i][1]+2);
timer[i+1][1]=min(timer[i][0]+2,timer[i][1]+2);
大写字母: timer[i+1][0]=min(timer[i][0]+2,timer[i][1]+2);
timer[i+1][1]=min(timer[i][0]+2,timer[i][1]+1);
1
#include
<
stdio.h
>
2 #include < string .h >
3 char str[ 110 ];
4 int timer[ 120 ][ 2 ];
5 #define min(a,b) (a)<(b)?(a):(b)
6 int main()
7 {
8 int num;
9 scanf( " %d\n " , & num);
10 while (num -- )
11 {
12 gets(str);
13 int len = strlen(str);
14 memset(timer, 0 , sizeof (timer));
15 timer[ 0 ][ 1 ] = 1 ;
16 for ( int i = 0 ;i < len;i ++ )
17 {
18 if (str[i] >= ' a ' && str[i] <= ' z ' )
19 {
20 timer[i + 1 ][ 0 ] = min(timer[i][ 0 ] + 1 ,timer[i][ 1 ] + 2 );
21 timer[i + 1 ][ 1 ] = min(timer[i][ 0 ] + 2 ,timer[i][ 1 ] + 2 );
22 }
23 else
24 {
25 timer[i + 1 ][ 0 ] = min(timer[i][ 0 ] + 2 ,timer[i][ 1 ] + 2 );
26 timer[i + 1 ][ 1 ] = min(timer[i][ 0 ] + 2 ,timer[i][ 1 ] + 1 );
27 }
28 }
29 printf( " %d\n " ,min(timer[len][ 0 ],timer[len][ 1 ] + 1 )); // 此处在tab开启状态时加1表示最后结尾要关闭tab键
30 }
31 return 0 ;
32 }
2 #include < string .h >
3 char str[ 110 ];
4 int timer[ 120 ][ 2 ];
5 #define min(a,b) (a)<(b)?(a):(b)
6 int main()
7 {
8 int num;
9 scanf( " %d\n " , & num);
10 while (num -- )
11 {
12 gets(str);
13 int len = strlen(str);
14 memset(timer, 0 , sizeof (timer));
15 timer[ 0 ][ 1 ] = 1 ;
16 for ( int i = 0 ;i < len;i ++ )
17 {
18 if (str[i] >= ' a ' && str[i] <= ' z ' )
19 {
20 timer[i + 1 ][ 0 ] = min(timer[i][ 0 ] + 1 ,timer[i][ 1 ] + 2 );
21 timer[i + 1 ][ 1 ] = min(timer[i][ 0 ] + 2 ,timer[i][ 1 ] + 2 );
22 }
23 else
24 {
25 timer[i + 1 ][ 0 ] = min(timer[i][ 0 ] + 2 ,timer[i][ 1 ] + 2 );
26 timer[i + 1 ][ 1 ] = min(timer[i][ 0 ] + 2 ,timer[i][ 1 ] + 1 );
27 }
28 }
29 printf( " %d\n " ,min(timer[len][ 0 ],timer[len][ 1 ] + 1 )); // 此处在tab开启状态时加1表示最后结尾要关闭tab键
30 }
31 return 0 ;
32 }