HDOJ 5569 matrix(简单DP)



matrix

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 121    Accepted Submission(s): 83


Problem Description
Given a matrix with n rows and m columns ( n+m is an odd number ), at first , you begin with the number at top-left corner (1,1) and you want to go to the number at bottom-right corner (n,m). And you must go right or go down every steps. Let the numbers you go through become an array a1,a2,...,a2k . The cost is a1a2+a3a4+...+a2k1a2k . What is the minimum of the cost?
 

Input
Several test cases(about 5 )

For each cases, first come 2 integers,
n,m(1n1000,1m1000)

N+m is an odd number.

Then follows
n lines with m numbers ai,j(1ai100)
 

Output
For each cases, please output an integer in a line as the answer.
 

Sample Input
   
   
   
   
2 3 1 2 3 2 2 1 2 3 2 2 1 1 2 4
 

Sample Output
   
   
   
   
4 8
 

题意: 给定一个n*m的矩阵(n+m为奇数),从(1,1)到(n,m)只能向右或者向下走。假设经过的路为a1,a2,a3,a4,a5,a6........,则花费值为a1*a2+a3*a4+a5*a6+.......,求最小花费。

真是SB了,听谷巨说了是DP,思路也对了,搞了半天,边界问题搞蒙了。
代码如下:

#include<cstdio>
#include<cstring>
#define INF 0x3f3f3f
int a[1010][1010];
int dp[1010][1010];

int min(int a,int b)
{
	return a>b?b:a;
}

int main()
{
	int n,m,i,j;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(i=0;i<n;++i)
			for(j=0;j<m;++j)
			{
				scanf("%d",&a[i][j]);
				dp[i][j]=INF;
			}
		if(n>0) dp[1][0]=a[0][0]*a[1][0];
		if(m>0)	dp[0][1]=a[0][0]*a[0][1];
		for(i=0;i<n;++i)
		{
			for(j=0;j<m;j++)
			{
				if((i+j)&1)
				{
					if(i-1>=0&&j-1>=0)
						dp[i][j]=dp[i-1][j-1]+a[i][j]*min(a[i-1][j],a[i][j-1]);
					if(i-2>=0)
						dp[i][j]=min(dp[i][j],dp[i-2][j]+a[i][j]*a[i-1][j]);
					if(j-2>=0)
						dp[i][j]=min(dp[i][j],dp[i][j-2]+a[i][j]*a[i][j-1]);
				}
			}
		} 
		printf("%d\n",dp[n-1][m-1]);
	}
	return 0;
} 

你可能感兴趣的:(HDOJ 5569 matrix(简单DP))