7.16笔记
shenhuo2013
·
·
个人记录
字符数:\color{#52C41A}\text{3314}
笔记
# 上午
## 单调栈
给出一个序列 $a_{1...n}$,你需要在 $1\le i \le n$ 中求出 $d_1$,表示 $a_i$ 之前第一个大于 $a_i$ 的数的索引。
需要对前缀 $a_{1...i}$ 计算集合____(一个大长式子)
$\color{#E74C3C}\text{*}$ $S(i+1)$ 必定是 $S(i)$ 中删去对应的 $a$ 不超过 $a_{i+1}$ 的索引再加上 $i+1$ 得到的。
单调栈代码:
```cpp
int sta[N + 1], top, a[N + 1], n, d[N + 1], e[N + 1];
void process() {
for (int i = 1; i <= n; i++) {
while (top && a[sta[top]] <= a[i])
e[sta[top]] = i, top--;
a[++top] = i;
if (top) d[i] = sta[top];
}
}
}
```
完整单调栈:
```cpp
int sta[N + 1], top, a[N + 1], n, d[N + 1], e[N + 1];
long long solve() {
a[0] = a[n + 1] = 1e6 + 1;
for (int i = 0; i <= n + 1; i++) {
while (top && a[sta[top]] <= a[i])
e[sta[top]] = i, top--;
a[++top] = i;
if (top) d[i] = sta[top];
}
long long ans = 0;
for (int i = 1; i <= n; i++)
ans += 1ll * a[i] * (i - d[i]) * (e[i] - i);
return ans;
}
```
## 单调(双端)队列
双端队列可以用于实现单调队列。
代码:
```cpp
int q[N + 1], top, a[N + 1], n, l[M + 1], r[M + 1], m;
void process() {
int head = 0, tail = 0, R = 0;
for (int i = 1; i <= m; i++) {
while (R < r[i]) {
R++;
while (tail - head && a[q[tail - 1]] <= a[R])
tail--;
q[tail++] = R;
}
while (tail - head && q[head] < l[i]) head++;
// ... (此时队列中元素即为 S(l[i],r[i]) 中的元素
// 从小到大排列后的结果)
}
}
```
P1886 部分代码:
```cpp
int a[N + 1], n, ans[N + 1], q[N + 1];
// 最终 ans[i] 存放的是以下标 i 结尾的区间的答案。
void process() {
int head = 0, tail = 0;
for (int i = 1; i <= n; i++) {
while (tail - head && a[q[tail - 1]] <= a[i]) tail--;
q[tail++] = i;
if (i > k && q[head] <= i - k) head++;
if (i >= k) ans[i] = a[q[head]];
}
}
```
## 例题:
[P5788](https://www.luogu.com.cn/problem/P5788)
$\color{#52C41A}\text{100}
P1886
\color{#52C41A}\text{100}
P2216
\color{#52C41A}\text{100}
STL
从 C++ 17 起,可以使用 “结构化绑定” 来解包一个 tuple 对象。
auto [a, b, c] = std::make_tuple(1, 2, 3);
- 以上操作同样适用于 tuple。
- tuple 之间也可以比较,同理为字典序。
`bitset` 定义在头文件 `<algorithm>` 中,可以理解为存储 `0` 和 `1` 两种元素的数组。其中每个元素被称为一个 “位”。
它与普通的数组不同之处,在与它用一列整数压缩存储其中
的位。
假设一个 `bitset` 中有 $n$ 个位,那么它占用的空间是 `O(n/w)` 的,其中 `w` 代表在计算机中一个 “字” 拥有的位数,
在 $32$ 位计算机上它是 `32`,在 $64$ 位计算机上它是 `64`。
`vector` 中的元素可以像数组那样用中括号访问(下标也是
从 $0$ 开始),也可以使用 `.at` 成员函数传入下标访问。两种
方式都将得到元素的引用,故可以通过这两种方式实现值的
修改。
`vector` 提供 `.front` 和 .back 成员函数,访问头部元素和
尾部元素。
`vector` 可以通过 `.begin` 和 `.end` 函数获取 vector 中第一
个元素和最后一个元素的后面一个位置的迭代器,也可以使
用 `.rbegin` 和 `.rend` 获取反向的两个迭代器。
仿函数:
```cpp
struct cmp {
bool operator () (int x, int y) { return x < y; }
};
```
## 例题:
$\color{#0E90D2}\text{*}$[P1956](https://www.luogu.com.cn/problem/P1956)
$\color{#52C41A}\text{100(已经提交题解审核)}
下午
邻接表的几种写法:
- 基于数组的邻接表
- 面向对象的邻接表
- 基于vector的邻接表
深搜实现方法:(图略)
例题:
P3916
\color{#52C41A}\text{100}
P1807
\color{#52C41A}\text{100}
$\color{#52C41A}\text{100}
一种特殊的有向图,没有任何环,通常简写为 DAG .对于这种图,我们就有“拓扑序”。
每次删去一个没有入度的点加入拓扑序中,如此重复下去即可。(图略)
名词解释:
-
根节点 叶节点 子树
-
有根树 无根树
-
父亲 祖先 兄弟 后代
-
无根树变有根树(随意确定一个点为根)
我们通常通过如下算法求树上最长路:
- 随意取一个点 A,找到离 A 最远的点 B
- 找到离 B 最远的点 C
- 输出 B 和 C