B4571题解
题意简述
维护两个可重集合:单词集合 、限制集合 ,一共有 m 次操作,分为两类:
add s:把字符串 加入单词集合query s x:往限制集合 添加一条限制 。 限制 的含义:集合 中,至少有 个字符串,使得 是该字符串的前缀。 每次操作结束之后,需要判断限制集合 R 内所有限制是否全部满足。全部满足输出 ,否则输出 。
核心思路
维护全局变量 :还没有满足的限制总数。 输出 。 Trie 每个节点:
- :经过该节点的字符串数量(前缀计数,只增不减)。
- 小根堆:存挂在这个节点上的所有未满足的限制 。
query s x:走到 对应的节点- 如果 :直接满足,不处理。
- 否则: 压入 的小根堆,
bad++。
add s:沿着 的字符走 Trie,沿途每个节点 :cnt_u++。- 循环:堆不为空并且堆顶 ,弹出堆顶,
bad--。
优势:堆自带有序,完全删掉动态 sort,解决之前最大的卡常点!
复杂度
总字符量 ,每条限制入堆一次、出堆一次。总复杂度 ,常数远小于带 sort 的 vector 版本。
样例解释
输入:
6
add a
query a 2
add ab
add ac
query ab 2
add abc输出:
Yes
No
Yes
Yes
No
Yes以第三次操作为例:
前三次操作完成后,,。
考虑 限制是否被满足:在集合 中的字符串里, 是 的前缀, 是 的前缀,因此恰好有 个字符串满足条件。该限制被满足,所以输出 Yes。
逻辑和刚刚推理的简直就是一模一样 😊。
易氧AC代码
//必须开O2QoQ好像吧,我懒得测
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000010;
struct Node {
int son[26];
int cnt;
priority_queue<int, vector<int>, greater<int>> q;
Node() {
memset(son, 0, sizeof son);
cnt = 0;
}
} trie[MAXN];
int tot = 1;
long long bad = 0;
inline void insert(const char *s) {
int u = 1;
for (; *s; ++s) {
int c = *s - 'a';
if (!trie[u].son[c]) {
trie[u].son[c] = ++tot;
}
u = trie[u].son[c];
trie[u].cnt++;
auto &hp = trie[u].q;
while (!hp.empty() && hp.top() <= trie[u].cnt) {
hp.pop();
bad--;
}
}
}
inline void add_query(const char *s, int x) {
int u = 1;
for (; *s; ++s) {
int c = *s - 'a';
if (!trie[u].son[c]) {
trie[u].son[c] = ++tot;
}
u = trie[u].son[c];
}
if (trie[u].cnt < x) {
trie[u].q.push(x);
bad++;
}
}
char op[10], str[1000010];
int main() {
int m;
scanf("%d", &m);
while (m--) {
scanf("%s%s", op, str);
if (op[0] == 'a') {
insert(str);
} else {
int x;
scanf("%d", &x);
add_query(str, x);
}
puts(bad == 0 ? "Yes" : "No");
}
return 0;
}