hdu 4540 dp 记忆化搜索

来源:互联网 发布:锐捷交换机端口聚合 编辑:程序博客网 时间:2024/06/07 16:16

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4540


思路:比较简单的一道dp题,设dp[i][j]为第i个时刻砸第j只地鼠所需最小的能量,dp[i][j]=min(dp[i][j], dp[i-1][e]),0<=e<k;

用记忆化搜索写出来。


#include <cstdio>#include <cstring>#include <vector>#include <cmath>#include <algorithm>using namespace std;const int inf = 0x3f3f3f3f;int a[30][30];int dp[30][30];int n, k, u;int dfs(int cur, int pos){    if(cur >= n) return 0;    int &res = dp[cur][pos];    if(res != inf) return res;    for(int i=0; i<k; i++)    {        res = min(res, dfs(cur+1, i)+abs(a[cur+1][i] - a[cur][pos]));    }    return res;}int main(){    while(~scanf("%d%d", &n, &k))    {        for(int i=1; i<=n; i++)        {            for(int j=0; j<k; j++)            {                scanf("%d", &a[i][j]);            }        }        memset(dp, 0x3f, sizeof(dp));        int ans = inf;        for(int i=0; i<k; i++)            ans = min(ans, dfs(1,i));        printf("%d\n", ans);    }    return 0;}


0 0