Find a path
Frog fell into a maze. This maze is a rectangle containing (N+M−1)∑i=1N+M−1(Ai−Aavg)2
In Frog's opinion, the smaller, the better. A path with smaller beauty value is more beautiful. He asks you to help him find the most beautiful path.
In Frog's opinion, the smaller, the better. A path with smaller beauty value is more beautiful. He asks you to help him find the most beautiful path.
InputThe first line of input contains a number Y is the minimum beauty value.Sample Input
1 2 2 1 2 3 4
Sample Output
Case #1: 14
将公式变形得:(n+m-1)*ΣAi^2-(ΣAi)^2
dp求出每种和的最小的平方和,最后找出满足公式的最小解。
#include<bits/stdc++.h> #define MAX 31 #define INF 0x3f3f3f3f using namespace std; typedef long long ll; int a[MAX][MAX]; int dp[MAX][MAX][1801]; int main() { int tt=0,t,n,m,i,j,k; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); for(i=1;i<=n;i++){ for(j=1;j<=m;j++){ scanf("%d",&a[i][j]); } } memset(dp,INF,sizeof(dp)); dp[1][0][0]=0;dp[0][1][0]=0; for(i=1;i<=n;i++){ for(j=1;j<=m;j++){ for(k=0;k<=1800;k++){ if(k+a[i][j]<=1800) dp[i][j][k+a[i][j]]=min(dp[i][j][k+a[i][j]],min(dp[i-1][j][k],dp[i][j-1][k])+a[i][j]*a[i][j]); } } } int ans=INF; for(i=0;i<=1800;i++){ if(dp[n][m][i]!=INF){ ans=min(ans,(n+m-1)*dp[n][m][i]-i*i); } } printf("Case #%d: %d\n",++tt,ans); } return 0; }