版本比较
题解 P1295 【[TJOI2011]书架】
正文
增加 11 行删除 11 行
55 行未改动565758596060616263649 行未改动7475767778787980818215 行未改动989910010110210210310410510610710510610710810911011011111211211311411511611511611711811811912012112216 行未改动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 值 // 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); // 队头的情况要特判 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) { 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 行未改动