题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=4540
简单的动归题。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
int map[25][25];
int dp[25][25];
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int n,k;
while(scanf(" %d %d",&n,&k)!=EOF)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=k;j++)
{
scanf(" %d",&map[i][j]);
}
}
memset(dp,0,sizeof(dp));
for(int i=2;i<=n;i++)
{
for(int j=1;j<=k;j++)
{
dp[i][j] = dp[i-1][1] + abs(map[i][j] - map[i-1][1]);
for(int h=2;h<=k;h++)
{
dp[i][j] = min(dp[i][j],dp[i-1][h] + abs(map[i][j] - map[i-1][h]));
}
}
}
int min_energy = 0x3f3f3f3f;
for(int i=1;i<=k;i++)
{
min_energy = min(min_energy,dp[n][i]);
}
printf("%d\n",min_energy);
}
}