您的位置:首页 > 其它

hdu 4540 dp 记忆化搜索

2016-04-19 00:09 274 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息