dp[ i ][ j ] 表示当前到处理完前 i 个, 其中一个子串最后一位时 i , 另一个子串最后一位是 j 的最大值。
随便维护一下就能转移了。
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 5000 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} int n, a[N], b[N]; int maxdp1[N][N]; int maxdp2[N][7]; int dp[N][N]; int hs[N], tot; int toS[N], toB[N]; int main() { memset(maxdp1, 0xc0, sizeof(maxdp1)); memset(maxdp2, 0xc0, sizeof(maxdp2)); scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); hs[++tot] = a[i]; } sort(hs + 1, hs + 1 + tot); tot = unique(hs + 1, hs + 1 + tot) - hs - 1; for(int i = 1; i <= n; i++) { b[i] = lower_bound(hs + 1, hs + 1 + tot, a[i]) - hs; if(binary_search(hs + 1, hs + 1 + tot, a[i] - 1)) toS[i] = b[i] - 1; else toS[i] = -1; if(binary_search(hs + 1, hs + 1 + tot, a[i] + 1)) toB[i] = b[i] + 1; else toB[i] = -1; } int ans = 0; for(int i = 1; i <= n; i++) { dp[i][0] = 1; if(~toS[i]) chkmax(dp[i][0], maxdp1[0][toS[i]] + 1); if(~toB[i]) chkmax(dp[i][0], maxdp1[0][toB[i]] + 1); chkmax(dp[i][0], maxdp2[0][a[i] % 7] + 1); for(int j = 1; j < i; j++) { dp[i][j] = 2; if(~toB[i]) chkmax(dp[i][j], maxdp1[j][toB[i]] + 1); if(~toS[i]) chkmax(dp[i][j], maxdp1[j][toS[i]] + 1); chkmax(dp[i][j], maxdp2[j][a[i] % 7] + 1); chkmax(dp[i][j], dp[j][0] + 1); chkmax(ans, dp[i][j]); } chkmax(maxdp1[0][b[i]], dp[i][0]); chkmax(maxdp2[0][a[i] % 7], dp[i][0]); for(int j = 1; j < i; j++) { chkmax(maxdp1[j][b[i]], dp[i][j]); chkmax(maxdp2[j][a[i] % 7], dp[i][j]); chkmax(maxdp1[i][b[j]], dp[i][j]); chkmax(maxdp2[i][a[j] % 7], dp[i][j]); } } printf("%d ", ans); return 0; } /* */