题解:B4571 [合肥市初中组 2025 T3] 字符串
love_zhang · · 题解
题目传送门
AC记录
B4571题解
题意简述
维护两个可重集合:单词集合
add s:把字符串s 加入单词集合D query s x:往限制集合R 添加一条限制(s,x) 。 限制(s,x) 的含义:集合D 中,至少有x 个字符串,使得s 是该字符串的前缀。 每次操作结束之后,需要判断限制集合 R 内所有限制是否全部满足。全部满足输出Yes ,否则输出No 。核心思路
维护全局变量
\mathit{bad} :还没有满足的限制总数。\mathit{bad}=0 输出Yes 。 Trie 每个节点:
-
- 小根堆:存挂在这个节点上的所有未满足的限制
x 。
query s x:走到s 对应的节点u - 如果
cnt_u \ge x :直接满足,不处理。 - 否则:
x 压入u 的小根堆,bad++。
- 如果
add s:沿着s 的字符走 Trie,沿途每个节点u :cnt_u++。- 循环:堆不为空并且堆顶
\le cnt_u ,弹出堆顶,bad \leftarrow bad +1 。优势:堆自带有序,完全删掉动态 sort,解决之前最大的卡常点!
复杂度
总字符量
S ,每条限制入堆一次、出堆一次。总复杂度O(S + Q\log Q) ,常数远小于带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;
}