hdu4618 Palindrome Sub-Array dp+记忆化搜索 或者直接暴力
题意就是找一个 左右上下对称的正方形矩阵。
连接:http://acm.hdu.edu.cn/showproblem.php?pid=4618
没想到记忆+dp和暴力就能水过。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//记忆话搜索+dp #include <iostream> #include <string.h> #include <stdio.h> #include <stdlib.h> using namespace std; int a[301][301]; char dp[301][301][301]; int n,m; int judge(int i,int j,int len) { int k; if(i+len-1 >= n) return 0; if(j+len-1 >= m) return 0; for(k = 0;k < len/2;k++) { if(a[i+k][j] != a[i+len-k-1][j]) return 0; } for(k = 0;k < len/2;k++) { if(a[i][j+k] != a[i][j+len-k-1]) return 0; } return len; } int dfs(int i,int j,int len) { if(dp[i][j][len] != -1) return dp[i][j][len]; if(len == 1 || len == 0) return dp[i][j][len] = 1; int leap; if(judge(i,j,len)) { leap = dfs(i+1,j+1,len-2); if(leap) { return dp[i][j][len] = 1; } } return dp[i][j][len] = 0; } int main() { int t; cin>>t; int count = 0; while(t--) { count++; int i,j; scanf("%d %d",&n,&m); for(i = 0;i < n;i++) for(j = 0;j < m;j++) scanf("%d",&a[i][j]); int len; len = min(n,m); int k; int ans; ans = 0; int ai,bj; memset(dp,-1,sizeof(dp)); for(i = 0;i < n;i++) { for(j = 0;j < m;j++) for(k = len;k >= 1;k--) { if(k > ans) { if(dfs(i,j,k)) { ans = k; break; } } } } printf("%d\n",ans); } return 0; }
暴力代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <string.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 using namespace std; 6 7 int a[305][305]; 8 int dp[305][305][305]; 9 int n,m; 10 int judge(int i,int j,int len) 11 { 12 int k,p; 13 if(i+len-1 >= n) return 0; 14 if(j+len-1 >= m) return 0; 15 for(p = 0;p < len;p++){ 16 for(k = 0;k < len/2;k++) 17 { 18 if(a[i+k][j+p] != a[i+len-k-1][j+p]) 19 return 0; 20 } 21 for(k = 0;k < len/2;k++) 22 { 23 if(a[i+p][j+k] != a[i+p][j+len-k-1]) 24 return 0; 25 } 26 } 27 return len; 28 } 29 int main() 30 { 31 int t; 32 33 cin>>t; 34 int count = 0; 35 while(t--) 36 { 37 count++; 38 int i,j; 39 scanf("%d %d",&n,&m); 40 for(i = 0;i < n;i++) 41 for(j = 0;j < m;j++) 42 scanf("%d",&a[i][j]); 43 44 int len; 45 len = min(n,m); 46 int k; 47 48 int ans; 49 ans = 0; 50 int ai,bj; 51 for(i = 0;i < n;i++) 52 { 53 for(j = 0;j < m;j++) 54 for(k = len;k >= 1;k--) 55 { 56 if(k > ans) 57 { 58 if(judge(i,j,k)) 59 { 60 ans = k; 61 break; 62 } 63 } 64 } 65 } 66 printf("%d\n",ans); 67 } 68 return 0; 69 }