【DP】hotel 题解 浅谈动态规划中的状态设计方法

有n个房间,每个房间里有少于七个人,两个相邻房间距离为一,每个房间可以住0或4或7个人,求总移动距离最小。
直观感受DP设计为dp[i][j],第一维表示房间,第二位表示人数,然后发现根本做不了。(欢声笑语打出GG)
那么我们不妨想象每两个房间之间有一条通道,每条通道单向通过的最多人数不超过7。(可以通过反证法得出通过超过7一定不优)
于是有了巧妙的状态设计,dp[i][j]第一维表示第i条通道,j表示通过人数(双向),那么如果转移之后可以使下一个房间合法则转移。初始状态定义一个假通道,出入为0。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <stack>
#define INF 2147483647
#define LL long long
#define clr(x) memset(x, 0, sizeof x)
#define digit (ch <  '0' || ch >  '9')

using namespace std;

template <class T> inline void read(T &x) {
    int flag = 1; x = 0;
    register char ch = getchar();
    while( digit) { if(ch == '-')  flag = -1; ch = getchar(); }
    while(!digit) { x = (x<<1)+(x<<3)+ch-'0'; ch = getchar(); }
    x *= flag;
}

int n;
LL dp[100020][15],a[100020],ans = INF;

inline bool check(int t) { return (!t || t == 4 || t == 7); }

int main() {
    freopen("hotel.in","r",stdin);
    freopen("hotel.out","w",stdout);
    memset(dp, 0x3f, sizeof dp); read(n);
    for(register int i = 1; i <= n; i++) read(a[i]);
    dp[0][7] = 0;
    for(register int i = 0; i < n; i++)
        for(register int j = 0; j <= 14; j++) if(dp[i][j] < INF)
            for(register int k = 0; k <= 14; k++) if(check(a[i+1]-j+k))
                dp[i+1][k] = min(dp[i][j]+abs(k-7), dp[i+1][k]);
    for(register int i = 0; i <= 14; i++) if(check(a[n]-i+7)) ans = min(ans, dp[n-1][i]);
    printf(ans >= INF ? "-1" : "%d",ans);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值