[题目链接]
https://www.lydsy.com/JudgeOnline/problem.php?id=3747
[算法]
首先 , 预处理nxt[i]表示下一个和第i天放映同样电影的是哪一天
枚举左端点 , 不妨计算以每个点为右端点所能获得“好看值”的总和 , 当左端点右移一位时 , [i , nxt[i] - 1]的答案减少了w[f[i]] , [nxt[i] , nxt[nxt[i]] - 1]的答案增加了w[f[i]]
维护一棵支持区间修改 , 维护最值的线段树即可
时间复杂度 : O(NlogN)
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXN 1000010 typedef long long LL; int n , m; LL f[MAXN] , w[MAXN]; int last[MAXN] , nxt[MAXN]; struct Segment_Tree { struct Node { int l , r; LL mx , tag; } Tree[MAXN << 2]; inline void build(int index , int l , int r) { Tree[index] = (Node){l , r , 0 , 0}; if (l == r) return; int mid = (l + r) >> 1; build(index << 1 , l , mid); build(index << 1 | 1 , mid + 1 , r); } inline void pushdown(int index) { Tree[index << 1].mx += Tree[index].tag; Tree[index << 1 | 1].mx += Tree[index].tag; Tree[index << 1].tag += Tree[index].tag; Tree[index << 1 | 1].tag += Tree[index].tag; Tree[index].tag = 0; } inline void update(int index) { Tree[index].mx = max(Tree[index << 1].mx , Tree[index << 1 | 1].mx); } inline void modify(int index , int l , int r , LL value) { if (Tree[index].l == l && Tree[index].r == r) { Tree[index].mx += value; Tree[index].tag += value; return; } pushdown(index); int mid = (Tree[index].l + Tree[index].r) >> 1; if (mid >= r) modify(index << 1 , l , r , value); else if (mid + 1 <= l) modify(index << 1 | 1 , l , r , value); else { modify(index << 1 , l , mid , value); modify(index << 1 | 1 , mid + 1 , r , value); } update(index); } inline LL query() { return Tree[1].mx; } } SGT; template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); } template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); } template <typename T> inline void read(T &x) { T f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } int main() { read(n); read(m); for (int i = 1; i <= n; i++) read(f[i]); for (int i = 1; i <= m; i++) read(w[i]); for (int i = n; i >= 1; i--) { nxt[i] = last[f[i]]; last[f[i]] = i; } SGT.build(1 , 1 , n); for (int i = 1; i <= m; i++) { if (last[i]) { if (!nxt[last[i]]) SGT.modify(1 , last[i] , n , w[i]); else SGT.modify(1 , last[i] , nxt[last[i]] - 1 , w[i]); } } LL ans = 0; for (int i = 1; i <= n; i++) { chkmax(ans , SGT.query()); if (nxt[i]) { SGT.modify(1 , i , nxt[i] - 1 , -w[f[i]]); if (nxt[nxt[i]]) SGT.modify(1 , nxt[i] , nxt[nxt[i]] - 1 , w[f[i]]); else SGT.modify(1 , nxt[i] , n , w[f[i]]); } else SGT.modify(1 , i , n , -w[f[i]]); } printf("%lld\n" , ans); return 0; }