1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 typedef long long LL; 6 7 const int MOD = 1e9 + 7; 8 9 class PalindromicSubseq2 { 10 public: 11 int solve(string s) { 12 int n = s.size(); 13 string t(s.rbegin(), s.rend()); 14 vector<vector<int>> dp(3001, vector<int>(3001, 0)); 15 for (int i = 0; i <= n; i++) { 16 dp[i][0] = 1; 17 dp[0][i] = 1; 18 } 19 for (int i = 1; i <= n; i++) { 20 // 虽然dp[i - 1][j] + dp[i][j - 1]肯定包含dp[i - 1][j - 1],但是取模后前两者可能小于后者导致结果为负,因此切记要+MOD 21 for (int j = 1; j <= n; j++) { 22 if (s[i - 1] == t[j - 1]) dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % MOD; 23 else dp[i][j] = ((dp[i - 1][j] + dp[i][j - 1]) % MOD - dp[i - 1][j - 1] + MOD) % MOD; 24 } 25 } 26 int res = 0; 27 for (int i = 0; i < n; i++) { 28 res ^= (i + 1) * (long long)dp[i][n - i - 1] % MOD; 29 } 30 return res; 31 } 32 };
时间: 2024-12-13 04:15:52