HDU 3651 DP

/********************************************************************************
    很有意思的DP,考虑状态dp[i][j][k],表示对于第i个字母,左手手指在j和右手手指在k的
时候需要的最小操作。最后取结果的时候要注意下,有左手手指在最后一位和右手手指在最后一
位这两种情况。其他就是细节问题了~
********************************************************************************/
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <utility>
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
#include <map>
#include <set>
using namespace std;

typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef map<int, int>::iterator MI;
typedef vector<int>::iterator VI;
typedef set<int>::iterator SI;

const int INF_INT = 0x3f3f3f3f;
const double oo = 10e9;
const double eps = 10e-7;
const double PI = acos(-1.0);

const int MAXN = 104;

int str[MAXN], dp[2][12][12];

inline int iabs(int x)
{
    return x < 0 ? -x : x;
}
void ace()
{
    char ch[MAXN];
    int len, res;
    int crt, step;
    while(gets(ch))
    {
        len = strlen(ch);
        for(int i = 0; i < len; ++i)
        {
            str[i] = ('0' == ch[i] ? 9 : ch[i] - '1');
        }
        memset(dp, INF_INT, sizeof(dp));
        dp[0][4][5] = 0;
        for(int i = 0, j = 0; j < len; i ^= 1, ++j)
        {
            memset(dp[i ^ 1], INF_INT, sizeof(dp[i ^ 1]));//这个地方原来写成sizeof(dp[i])了。。。
            for(int left = 0; left < 9; ++left)
            {
                for(int right = left + 1; right < 10; ++right)
                {
                    crt = str[j];
                    step = iabs(left - crt) + 1;
                    for(int pos = crt + 1; pos < 10; ++pos)
                    {
                        if(iabs(pos - right) > step)
                        {
                            continue ;
                        }
                        dp[i ^ 1][crt][pos] = min(dp[i ^ 1][crt][pos], dp[i][left][right] + step);
                    }
                    step = iabs(right - crt) + 1;
                    for(int pos = 0; pos < crt; ++pos)
                    {
                        if(iabs(pos - left) > step)
                        {
                            continue ;
                        }
                        dp[i ^ 1][pos][crt] = min(dp[i ^ 1][pos][crt], dp[i][left][right] + step);
                    }
                }
            }
        }
        res = INF_INT;
        crt = str[len - 1];
        for(int i = crt + 1; i < 10; ++i)
        {
            res = min(res, dp[len & 0x1][crt][i]);
        }
        for(int i = 0; i < crt; ++i)
        {
            res = min(res, dp[len & 0x1][i][crt]);
        }
        printf("%d\n", res);
    }
    return ;
}
int main()
{
    ace();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值