HDU 2859 Phalanx ——(DP)

  感觉是个n^3的dp,只是可能上界比较松吧。。转移见代码。值得注意的一个地方是如果n是1,那么在for里面是不会更新答案的,因此ans要初始化为1。

  代码如下:

 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <string.h>
 4 using namespace std;
 5 const int N = 1000 + 5;
 6 
 7 char s[N][N];
 8 int dp[N][N];
 9 int n;
10 
11 int main()
12 {
13     while(scanf("%d",&n) == 1 && n)
14     {
15         for(int i=1;i<=n;i++) scanf("%s",s[i]+1);
16         int ans = 1;
17         for(int i=1;i<=n;i++)
18         {
19             for(int j=n;j>=1;j--)
20             {
21                 dp[i][j] = 1;
22                 if(i == 1 || j == n) continue;
23                 int lim = dp[i-1][j+1];
24                 for(int k=1;k<=lim;k++)
25                 {
26                     if(s[i-k][j] == s[i][j+k]) dp[i][j]++;
27                     else break;
28                 }
29                 ans = max(ans, dp[i][j]);
30             }
31         }
32         printf("%d
",ans);
33     }
34     return 0;
35 }
原文地址:https://www.cnblogs.com/zzyDS/p/6408916.html