【动态规划】locker

locker

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1271    Accepted Submission(s): 549


Problem Description
A password locker with N digits, each digit can be rotated to 0-9 circularly.
You can rotate 1-3 consecutive digits up or down in one step.
For examples:
567890 -> 567901 (by rotating the last 3 digits up)
000000 -> 000900 (by rotating the 4th digit down)
Given the current state and the secret password, what is the minimum amount of steps you have to rotate the locker in order to get from current state to the secret password?
 

Input
Multiple (less than 50) cases, process to EOF.
For each case, two strings with equal length (≤ 1000) consists of only digits are given, representing the current state and the secret password, respectively.
 

Output
For each case, output one integer, the minimum amount of steps from the current state to the secret password.
 

Sample Input
  
  
111111 222222 896521 183995
 

Sample Output
  
  
2 12
 

Source
 

Recommend
zhoujiaqi2010   |   We have carefully selected several similar problems for you:   4812  4811  4810  4809  4808 
 
 
每次只能扳动一格。
暂讨论向上扳。
 
因为一次最多可以转动三格子。转移方程中涉及到了i,i+1,i+2的状态
f[i,j,k] 表示第i格已经扳到j,i+1格已经扳到k。前i-1个格子都到指定位置。的最小转动次数。
要把i格扳到指定位置,需要扳(s2[i]-s1[i]-j)%10次。
然而并不是每次都得转动i,i+1,i+2。也可以只转动i,i+1或只转动i。(我们可以想象成每次都是i主动转,带动后两个可转可不转)因此t>=a>=b。
(注意k和a的含义不同,j和t的含义也不同。因为j和k是之前被动地转,a是当前i+1被动地转,t是i主动在转)
 
向下转类似。
最后输出答案是最后一个格子后面两个格子都不转。
 
 
这道题的启示是:
1、无序有序化,有时就可以消除后效性(当然要利用一些手段比如整体看待)。
2、有多少元素参与转移,常常就会有多少元素在转移方程里,把它们当做一个整体来看待。
 
 
#include <cstdio>
#include <cstring>

int min(int a,int b)
{
    return a<b?a:b;
}


int f[1010][10][10];
char s1[1010];
char s2[1010];

int main()
{
    while (scanf("%s%s",s1,s2)!=EOF)
    {
        int len = strlen(s1);

        memset(f,0x3f,sizeof f);
        f[0][0][0] = 0;
        for (int i=0;i<len;i++)
        {
            for (int j=0;j<10;j++)
            {
                for (int k=0;k<10;k++)
                {
                    int t = (s2[i]-s1[i]-j+20)%10;
                    for (int a=0;a<=t;a++)
                    {
                        for (int b=0;b<=a;b++)
                        {
                            f[i+1][(k+a)%10][b] = min(f[i+1][(k+a)%10][b],f[i][j][k]+t);
                        }
                    }

                    t = 10-t;
                    for (int a=0;a<=t;a++)
                    {
                        for (int b=0;b<=a;b++)
                        {
                            f[i+1][(k-a+20)%10][(10-b)%10] = min(f[i+1][(k-a+20)%10][(10-b)%10],f[i][j][k]+t);
                        }
                    }
                }
            }
        }
        printf("%d\n",f[len][0][0]);

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值