正文
增加 11 行删除 11 行
55 行未改动5657585960616263649 行未改动74757677787980818215 行未改动989910010110210310410510610710810911011111211311411511611711811912012112216 行未改动55 行未改动**综上我们得到了一个 $O(n)$ 的算法。**## ※代码~~我知道你们只看这个~~```cpp/*BY xiejinhao9 行未改动int top[2], l = 1, mid, r;long long f[N], tmpf[N];// stk[0/1] 左/右 栈,指针对应 top[0/1]// q 队列 h 原数组 tmpf 对应队列中的 f 值void push(int x, int i) {if(!top[i]) stk[i][++top[i]] = x;else if(tmpf[stk[i][top[i]]] > tmpf[x])15 行未改动while(l <= r and h[q[r]] <= h[i]) {if(top[0] and stk[0][top[0]] == r) --top[0];if(top[1] and stk[1][top[1]] == r) --top[1];if(--r <= mid) rebuild();} // 维护单调队列if(l > r) tmpf[r + 1] = f[st - 1] + h[i];else tmpf[r + 1] = f[q[r]] + h[i];q[++r] = i, push(r, 1);// 队头的情况要特判if(stk[0][top[0]] == l) --top[0];if(stk[1][top[1]] == l) --top[1];while(l <= r and q[l] < st) {if(++l > mid) rebuild();// 同样特判队头if(top[0] and stk[0][top[0]] == l) --top[0];if(top[1] and stk[1][top[1]] == l) --top[1];} // 弹出过期元素f[i] = f[st - 1] + h[q[l]]; // 和开头并为一段// --- 与开头之后的某个数开始并为一段 ---if(top[0]) f[i] = min(f[i], tmpf[stk[0][top[0]]]);if(top[1]) f[i] = min(f[i], tmpf[stk[1][top[1]]]);}printf("%lld\n", f[n]);16 行未改动55 行未改动5657585960616263649 行未改动74757677787980818215 行未改动989910010110210310410510610710810911011111211311411511611711811912012112216 行未改动55 行未改动**综上我们得到了一个 $O(n)$ 的算法。**## ※代码~~我知道你们只看这个~~```cpp/*BY xiejinhao9 行未改动int top[2], l = 1, mid, r;long long f[N], tmpf[N];// stk[0/1] 左/右 栈,指针对应 top[0/1]// q 队列 h 原数组 tmpf 对应队列中的 f 值void push(int x, int i) {if(!top[i]) stk[i][++top[i]] = x;else if(tmpf[stk[i][top[i]]] > tmpf[x])15 行未改动while(l <= r and h[q[r]] <= h[i]) {if(top[0] and stk[0][top[0]] == r) --top[0];if(top[1] and stk[1][top[1]] == r) --top[1];if(--r <= mid) rebuild();} // 维护单调队列if(l > r) tmpf[r + 1] = f[st - 1] + h[i];else tmpf[r + 1] = f[q[r]] + h[i];q[++r] = i, push(r, 1);// 队头的情况要特判if(stk[0][top[0]] == l) --top[0];if(stk[1][top[1]] == l) --top[1];while(l <= r and q[l] < st) {if(++l > mid) rebuild();// 同样特判队头if(top[0] and stk[0][top[0]] == l) --top[0];if(top[1] and stk[1][top[1]] == l) --top[1];} // 弹出过期元素f[i] = f[st - 1] + h[q[l]]; // 和开头并为一段// --- 与开头之后的某个数开始并为一段 ---if(top[0]) f[i] = min(f[i], tmpf[stk[0][top[0]]]);if(top[1]) f[i] = min(f[i], tmpf[stk[1][top[1]]]);}printf("%lld\n", f[n]);16 行未改动