Topcoder SRM552 Div1 500

int FoxAndFlowerShopDivOne::theMaxFlowers(vector <string> flowers, int maxDiff)
{
    const int NN=1000;
	int n=flowers.size();
	int m=flowers[0].size();
	int l[32][32],p[32][32];
	int dpi[32][2000],dpj[32][2000],dp1[32][2000],dp2[32][2000];
	
	memset(l,0,sizeof(l));
	memset(p,0,sizeof(p));
	
	for (int i=0; i<n; i++)
	  for (int j=0; j<m; j++)
	  {
	      l[i+1][j+1]=l[i][j+1]+l[i+1][j]-l[i][j]+(flowers[i][j]=='P'); 
	      p[i+1][j+1]=p[i][j+1]+p[i+1][j]-p[i][j]+(flowers[i][j]=='L');
	  }
	  
	memset(dpi,-1,sizeof(dpi));
	memset(dpj,-1,sizeof(dpj));
	memset(dp1,-1,sizeof(dp1));//本来只用两个dp数组,新加的忘了初始化,总test不对,郁闷,负分了~
	memset(dp2,-1,sizeof(dp2));
	
	for (int i=1; i<=n; i++)
	  for (int j=1; j<=m; j++)
	    for (int u=i; u<=n; u++)
	      for (int v=j; v<=m; v++)
	      {
	          int tmpl=l[u][v]-l[u][j-1]-l[i-1][v]+l[i-1][j-1];
	          int tmpp=p[u][v]-p[u][j-1]-p[i-1][v]+p[i-1][j-1];
	          if (dpi[u][tmpl-tmpp+NN]<tmpl+tmpp) dpi[u][tmpl-tmpp+NN]=tmpl+tmpp;
	          if (dpj[v][tmpl-tmpp+NN]<tmpl+tmpp) dpj[v][tmpl-tmpp+NN]=tmpl+tmpp;
	          if (dp1[i][tmpl-tmpp+NN]<tmpl+tmpp) dp1[i][tmpl-tmpp+NN]=tmpl+tmpp;
	          if (dp2[j][tmpl-tmpp+NN]<tmpl+tmpp) dp2[j][tmpl-tmpp+NN]=tmpl+tmpp;
	      }
	      
	for (int i=2; i<=n; i++)
	  for (int x=0; x<=2*NN; x++) if (dpi[i-1][x]>dpi[i][x]) dpi[i][x]=dpi[i-1][x];
	  
	for (int j=2; j<=m; j++)
	  for (int x=0; x<=2*NN; x++) if (dpj[j-1][x]>dpj[j][x]) dpj[j][x]=dpj[j-1][x];
	
	for (int i=n-1; i; i--)
	  for (int x=0; x<=2*NN; x++) if (dp1[i+1][x]>dp1[i][x]) dp1[i][x]=dp1[i+1][x];
	  
	for (int j=m-1; j; j--)
	  for (int x=0; x<=2*NN; x++) if (dp2[j+1][x]>dp2[j][x]) dp2[j][x]=dp2[j+1][x];
	  
	int ans=-1;
	for (int i=1; i<n; i++)
	  for (int x=0; x<=2*NN; x++) if (dpi[i][x]!=-1)
	  {
	      int low=max(NN*2-maxDiff-x,0);
	      int high=min(NN*2+maxDiff-x,2*NN);
	      for (int y=low; y<=high; y++) if (dp1[i+1][y]!=-1)
	          if (dpi[i][x]+dp1[i+1][y]>ans) ans=dpi[i][x]+dp1[i+1][y];
	  }
	  
	for (int j=1; j<m; j++)
	  for (int x=0; x<=2*NN; x++) if (dpj[j][x]!=-1)
	  {
	      int low=max(NN*2-maxDiff-x,0);
	      int high=min(NN*2+maxDiff-x,2*NN);
	      for (int y=low; y<=high; y++) if (dp2[j+1][y]!=-1)
	          if (dpj[j][x]+dp2[j+1][y]>ans) ans=dpj[j][x]+dp2[j+1][y];
	  }
    return ans;
}

你可能感兴趣的:(Topcoder SRM552 Div1 500)