2015 ACM/ICPC Asia Regional Hefei Online Find a path
设\(A_{sum} = \sum_{i=1}^{n+m-1}A_i\)
然后 : \((n+m-1)\sum_{i=1}^{n+m-1}(A_i-A_{avg})^2 \\ = (n+m-1)\sum_{i=1}^{n+m-1}(A_i^2-2A_iA_{avg}+A_{avg}^2) \\ = A_{sum}^2 + \sum_{i=1}^{n+m-1}A_{i}^2-2A_{sum}A_{i}\)
最后退出来 ans = (n+m-1)\(\sum_{i}^(n+m-1)A_i^2 - (A_i)^2\)
然后,把方差式子变换一下,然后把和作为状态暴力dp即可
代码:
#include <iostream>
#include <stdio.h>
#include <sting.h>
#include <algorithm>
#define maxn 35
#define inf 0x3f3f3f3f
using namespace std ;
int s[maxn][maxn] ;
int dp[maxn][maxn][60*30*2] ;
int T , cas = 0 , n , m ;
int main () {
scanf("%d",&t) ;
while(t --) {
scanf("%d%d",&n,&m) ;
for(int i = 1 ; i <= n ; i ++) {
for(int j = 1 ; j <= m ; j ++) {
scanf("%d",&s[i][j]) ;
}
}
memset(dp,0x3f,sizeof(dp)) ;
f[1][0][0] = f[0][1][0] = 0 ;
for(int i = 1 ; i <= n ; i ++) {
for(int j = 1 ; j <= m ; j ++) {
int x = (n+m-1)*s[i][j] * s[i][j] , y = (i+j-1)*30 ;
for(int k = 0 ; k <= y ; k ++) {
f[i][j][k+s[i][j]] = min (f[i][j][k+s[i][j]],min(f[i-1][j][k],f[i][j-1][k])+x) ;
}
}
}
for(int i = 0 ; i <= 1800 ; i ++) {
ans = min(ans,f[n][m][i]-i*i) ;
printf("Case #%d: %d\n",++cas,ans);
}
}
return 0 ;
}
!我可不想再考一遍辣!