Source: HDU 3613 best reward
Question: each letter corresponds to a weight, which will divide your string into two parts. If one part is a retrieval, the value of this part is the sum of the weights of each letter. Evaluate a method to maximize the sum of the two parts.
Train of Thought: Extend KMP output string a to obtain the reverse string B of string a and obtain the reverse string B of string f [0] and f [1] and extend [0] and extend [1] twice.
Enumeration position I is divided into two parts 0 to I-1 and I to n-1 because the two parts must constitute the original string is not more or less
If I + extend [I] is equal to N, it means that the Part I to N-1 is the sum1 of the input string. If this part is not the input sum1 = 0
Judge 0 to the I-1 is not the back of the and B flip then and judge I to N-1 is the same, so the above positive and negative for 2 sum2 for this part of the value if this part is not the back of the sum2 = 0
The maximum value of sum1 + sum2. The value of another string can be obtained recursively.
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 500010;int f[2][maxn], ex[2][maxn];char a[maxn], b[maxn]; int id[26], dp[2][maxn];void getFail(char* s, int id, int n){int k = 1, p = 0;while(p+1 < n && s[p] == s[p+1])p++;f[id][0] = n;f[id][1] = p;for(int i = 2; i < n; i++){int l = f[id][i-k];int p = f[id][k]+k-1;if(i+l-1 < p)f[id][i] = l;else{int j = p-i+1;if(j < 0)j = 0;while(i+j < n && s[i+j] == s[j])j++;f[id][i] = j;k = i;}}}void getEx(char* s, char* t, int id, int n){int k = 0, p = 0;while(p < n && s[p] == t[p])p++;ex[id][0] = p;for(int i = 1; i < n; i++){int l = f[id^1][i-k];int p = ex[id][k]+k-1;if(i+l-1 < p)ex[id][i] = l;else{int j = p-i+1;if(j < 0)j = 0;while(i+j < n && s[i+j] == t[j])j++;ex[id][i] = j;k = i;}}}int main(){int T;scanf("%d", &T);while(T--){for(int i = 0; i < 26; i++)scanf("%d", &id[i]);scanf("%s", a); int n = strlen(a);for(int i = 0; i < n; i++){b[i] = a[n-i-1];if(i)dp[0][i] = id[a[i]-'a'] + dp[0][i-1];elsedp[0][i] = id[a[i]-'a'];}for(int i = 0; i < n; i++){if(i)dp[1][i] = dp[1][i-1] + id[b[i]-'a'];elsedp[1][i] = id[b[i]-'a'];}getFail(a, 0, n);getFail(b, 1, n);getEx(a, b, 0, n); getEx(b, a, 1, n);int ans = 0;for(int i = 1; i < n; i++){int sum1 = 0, sum2 = 0;if(i+ex[0][i] == n)sum1 = dp[1][ex[0][i]-1];int j = n-i;if(j+ex[1][j] == n)sum2 = dp[0][ex[1][j]-1];ans = max(ans, sum1+sum2);//printf("%d %d\n", ex[0][i], ex[1][i]);}printf("%d\n", ans);}return 0;}