题解:P11727 [JOIG 2025] 神経衰弱 2 / Pair Matching 2

· · 题解

树状数组优化 DP。

容易发现,两个相同的东西间隔不会超过一。

不选,$dp_i=dp_{i-1}$。 选,有两种。 第一种,$dp_i=dp_{pre_i}+v_{a_i}$。 第二种,$dp_i=dp_{pre_j}+v_{a_i}+v_{a_j}$,条件是 $pre_j<pre_i<j<i$。 然后树状数组优化,复杂度 $O(n \log n)$。 ```cpp #include<bits/stdc++.h> using namespace std; struct FSI{ template<typename T> FSI& operator >> (T &res){ res=0;T f=1;char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();} while (isdigit(ch)){res=res*10+ch-'0';ch=getchar();} res*=f; return *this; } }scan; typedef long long ll; const int N=4e5+10; int n,a[N<<1],v[N],i,j,pre[N<<1],last[N]; ll dp[N<<1],c[N<<1]; int lowbit(int x){return x&(-x);} void motify(int x,ll v) { int i; for (i=x;i<=2*n;i+=lowbit(i)) c[i]=max(c[i],v); } ll query(int x) { ll res=0,i; for (i=x;i>0;i-=lowbit(i)) res=max(res,c[i]); return res; } int main() { scan>>n; for (i=1;i<=2*n;i++) scan>>a[i]; for (i=1;i<=n;i++) scan>>v[i]; for (i=1;i<=2*n;i++) { pre[i]=last[a[i]]; last[a[i]]=i; } for (i=1;i<=2*n;i++) { dp[i]=dp[i-1]; if (pre[i]) { dp[i]=max(dp[i],dp[pre[i]]+v[a[i]]); dp[i]=max(dp[i],query(pre[i]-1)+v[a[i]]); motify(pre[i],dp[pre[i]]+v[a[i]]); } } printf("%lld",dp[2*n]); return 0; } ```