PTA最长回文子序列

一、题目描述

  

 

 二、解题思路

  这个题打比赛的时候以为是”马拉车“就直接跳过了,打完比赛回来想了两分钟发现这个题就是个LCS的模板题。亏大了!!!!直接把原串翻转,然后对原串和翻转后的原串做DP,最后dp[n][n]就是答案。

三、代码实现

 1 #include "bits/stdc++.h"
 2 using namespace std;
 3 int dp[1010][1010];
 4 string s;
 5 string cs;
 6 int main()
 7 {
 8     cin >> s;
 9     cs = s;
10     reverse(s.begin(),s.end());
11     int n = s.size();
12     for(int i = 1;i <= n;i++)
13         for(int j = 1;j <= n;j++)
14             if(s[i - 1] == cs[j - 1])
15                 dp[i][j] = dp[i - 1][j - 1] + 1;
16             else 
17                 dp[i][j] = max(dp[i - 1][j],dp[i][j - 1]);
18     cout << dp[n][n] << endl;
19     return 0;
20 }
posted @ 2022-03-15 15:25  scannerkk  阅读(33)  评论(0)    收藏  举报