首页 > 代码库 > 【动态规划】HDU 5492 Find a path (2015 ACM/ICPC Asia Regional Hefei Online)

【动态规划】HDU 5492 Find a path (2015 ACM/ICPC Asia Regional Hefei Online)

题目链接:

  http://acm.hdu.edu.cn/showproblem.php?pid=5492

题目大意:

  一个N*M的矩阵,一个人从(1,1)走到(N,M),每次只能向下或向右走。求(N+M-1)ΣN+M-1(Ai-Aavg)2最小。Aavg为平均值。

  (N,M<=30,矩阵里的元素0<=C<=30)

题目思路:

  【动态规划】

  首先化简式子,得原式=(N+M-1)ΣN+M-1(Ai2)-(ΣN+M-1Ai)2

  f[i][j][k]表示走到A[i][j]格子上,此时前i+j-1个值得和(Σi+j-1Ai)为K的平方和(Σi+j-1Ai2)最小值。

  向下或向右转移很好推。

  由于每个格子的值<=30,K<=59*30=1770.总时间复杂度为O(N*M*K)

 

技术分享
 1 // 2 //by coolxxx 3 //#include<bits/stdc++.h> 4 #include<iostream> 5 #include<algorithm> 6 #include<string> 7 #include<iomanip> 8 #include<map> 9 #include<stack>10 #include<queue>11 #include<set>12 #include<bitset>13 #include<memory.h>14 #include<time.h>15 #include<stdio.h>16 #include<stdlib.h>17 #include<string.h>18 //#include<stdbool.h>19 #include<math.h>20 #define min(a,b) ((a)<(b)?(a):(b))21 #define max(a,b) ((a)>(b)?(a):(b))22 #define abs(a) ((a)>0?(a):(-(a)))23 #define lowbit(a) (a&(-a))24 #define sqr(a) ((a)*(a))25 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))26 #define mem(a,b) memset(a,b,sizeof(a))27 #define eps (1e-8)28 #define J 1000029 #define mod 100000000730 #define MAX 0x7f7f7f7f31 #define PI 3.1415926535897932332 #define N 4433 using namespace std;34 typedef long long LL;35 int cas,cass;36 int n,m,lll,ans;37 LL aans;38 int a[N][N];39 int sum;40 int f[N][N][2004];41 void print()42 {43     int i,j,k;44     for(i=0;i<=sum;i++)45         printf("%d\n",f[n][m][i]);46 }47 int main()48 {49     #ifndef ONLINE_JUDGE50 //    freopen("1.txt","r",stdin);51 //    freopen("2.txt","w",stdout);52     #endif53     int i,j,k;54 55 //    for(scanf("%d",&cass);cass;cass--)56     for(scanf("%d",&cas),cass=1;cass<=cas;cass++)57 //    while(~scanf("%s",s+1))58 //    while(~scanf("%d",&n))59     {60         mem(f,MAX);61         sum=0;62         scanf("%d%d",&n,&m);63         for(i=1;i<=n;i++)64             for(j=1;j<=m;j++)65                 scanf("%d",&a[i][j]);66         f[0][1][0]=0;67         for(i=1;i<=n;i++)68         {69             for(j=1;j<=m;j++)70             {71                 for(k=a[i][j];k<=59*30;k++)72                 {73                     f[i][j][k]=min(f[i][j][k],f[i-1][j][k-a[i][j]]+sqr(a[i][j]));74                     f[i][j][k]=min(f[i][j][k],f[i][j-1][k-a[i][j]]+sqr(a[i][j]));75                 }76             }77         }78         ans=MAX;79         for(i=0;i<=59*30;i++)80         { 81             if(f[n][m][i]==f[0][0][0])continue;82             ans=min(ans,(n+m-1)*f[n][m][i]-sqr(i));83         }84         printf("Case #%d: %d\n",cass,ans);85     }86     return 0;87 }88 /*89 //90 91 //92 */
View Code

 

【动态规划】HDU 5492 Find a path (2015 ACM/ICPC Asia Regional Hefei Online)