Title
Portal Codeforces 1497D Genius
answer
Observe ∣ ci − cj ∣ \lvert c_i-c_j\rvert∣ci−cj∣,设 i < j i<j i<j , the result is the binary representation[i, j − 1] [i,j-1][i,j−1 ] bit is1 11 number; then for different(i, j) (i, j)(i,j) 对, ∣ c i − c j ∣ \lvert c_i-c_j\rvert ∣ci−cj∣The value is different. If the state is expressed as a two-tuple composed of the end point of the path and the maximum value that can be taken on the upper edge of the path, use∣ ci − cj ∣ \lvert c_i-c_j\rvert∣ci−cj∣Connect the edges for the edge rights, then get aDAG DAGD A G , and the edge weight on the path increases monotonically.
d p [ i ] [ k ] dp[i][k] d p [ i ] [ k ] represents the path withiii is the end point, and the maximum value that can be taken on the road strength iskkWhen k , the maximum number of points that can be obtained. Letk = ∣ ci − cj ∣ k=\lvert c_i-c_j\rvertk=∣ci−cj∣,且 t a g i ≠ t a g j tag_i\neq tag_j tagi=tagj设 设for (k) for (k)p r e ( k ) is less thankkk 的最大边权,则有
{ d p [ i ] [ k ] = max { d p [ i ] [ p r e ( k ) ] , d p [ j ] [ p r e ( k ) ] + ∣ c i − c j ∣ } d p [ j ] [ k ] = max { d p [ j ] [ p r e ( k ) ] , d p [ i ] [ p r e ( k ) ] + ∣ c i − c j ∣ } \begin{cases}dp[i][k]=\max\{dp[i][pre(k)],dp[j][pre(k)]+ \lvert c_i-c_j\rvert\}\\ dp[j][k]=\max\{dp[j][pre(k)],dp[i][pre(k)]+ \lvert c_i-c_j\rvert\}\end{cases} {
dp[i][k]=max{
dp[i][pre(k)],dp[j][pre(k)]+∣ci−cj∣}dp[j][k]=max{
dp[j][pre(k)],dp[i][pre(k)]+∣ci−cj∣}DP DP in increasing order of the edge weights that can be selectedDP,即 i ( 1 ≤ i ≤ n ) i(1\leq i\leq n) i(1≤i≤n) 递增, j ( 1 ≤ j ≤ i − 1 ) j(1\leq j\leq i-1) j(1≤j≤i−1 ) Decrease; realize the compression to one-dimensionalDP DPD P . Finally, enumerate the end of the path and update the answer.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5005;
int T, N, tag[maxn], s[maxn];
ll dp[maxn];
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d", &N);
for (int i = 1; i <= N; ++i)
scanf("%d", tag + i);
for (int i = 1; i <= N; ++i)
scanf("%d", s + i);
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= N; ++i)
for (int j = i - 1; j; --j)
{
if (tag[i] == tag[j])
continue;
ll xi = dp[i], xj = dp[j], d = abs(s[i] - s[j]);
dp[i] = max(dp[i], xj + d), dp[j] = max(dp[j], xi + d);
}
printf("%lld\n", *max_element(dp + 1, dp + N + 1));
}
return 0;
}