HDU 3651 DP

来源:互联网 发布:c语言取反!用法 编辑:程序博客网 时间:2024/05/16 13:55
/********************************************************************************    很有意思的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;}

原创粉丝点击