因为你是我的骄傲
假设最终聊了
令
若
设最后一次固定了
时间复杂度
namespace Loop1st {
int n, p[N], top;
ll a[N], b[N], A[N], S[N], suf[N], ans = -inf, s1, s2;
struct Node {
ll v;
int cnt;
} stk[N];
void Main(int tc) {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i] >> b[i], A[i] = A[i - 1] + a[i], S[i] = S[i - 1] + b[i];
int x = 0, u = 0;
for (int i = 1; i <= n; i++) {
cin >> p[i];
if (p[i] != -1) {
suf[p[i]] = S[p[i]];
for (int j = p[i] - 1; j >= u; j--) suf[j] = min(S[j], suf[j + 1]);
for (int t = x; t < i - 1; t++) s1 += suf[max(u, t + 1)];
s1 += S[p[i]];
x = i; u = p[i];
}
}
if (!x) ans = 0;
for (int i = 1; i <= u - x; i++) {
int cnt = 1;
while (top && stk[top].v >= S[u]) {
cnt += stk[top].cnt;
s2 -= stk[top].v * stk[top].cnt;
top--;
}
stk[++top] = {S[u], cnt};
s2 += S[u] * cnt;
}
ans = max(ans, A[u] + S[u] * u - s1 - s2);
for (int k = u + 1; k <= n; k++) {
int cnt = 1;
while (top && stk[top].v >= S[k]) {
cnt += stk[top].cnt;
s2 -= stk[top].v * stk[top].cnt;
top--;
}
stk[++top] = {S[k], cnt};
s2 += S[k] * cnt;
ans = max(ans, A[k] + S[k] * k - s1 - s2);
}
cout << ans << '\n';
}
}