题目传送门
中文翻译:
解题思路:
f[i][j]表示到第i行第j列时,可获得的最小收益
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 5 using namespace std; 6 7 long long n,m,a[1001][1001],f[1001][1001]; 8 9 int main() { 10 while(scanf("%d%d",&n,&m) != EOF) { 11 memset(a,0,sizeof(a)); 12 memset(f,0x3f3f3f,sizeof(f)); 13 for(int i = 1;i <= n; i++) 14 for(int j = 1;j <= m; j++) 15 scanf("%d",&a[i][j]); 16 f[1][1] = a[1][1]; 17 for(int i = 2;i <= m; i++) {//处理第一行 18 if(i % 2 == 0) f[1][i] = f[1][i-1] + a[1][i] * a[1][i-1]; 19 else f[1][i] = f[1][i-1]; 20 if(i == 2) f[1][2] -= f[1][1]; 21 } 22 for(int i = 2;i <= n; i++) {//处理第一列 23 if(i % 2 == 0) f[i][1] = f[i-1][1] + a[i][1] * a[i-1][1]; 24 else f[i][1] = f[i-1][1]; 25 if(i == 2) f[2][1] -= f[1][1]; 26 } 27 for(int i = 2;i <= n; i++) 28 for(int j = 2;j <= m; j++) { 29 if((j + i) % 2 == 0)//走了奇数步 30 f[i][j] = min(f[i-1][j],f[i][j-1]); 31 else //走了偶数步 32 f[i][j] = min(f[i-1][j] + a[i-1][j] * a[i][j],f[i][j-1] + a[i][j-1] * a[i][j]); 33 } 34 printf("%d ",f[n][m]); 35 } 36 return 0; 37 }