题解:B4571 [合肥市初中组 2025 T3] 字符串

· · 题解

题目传送门
AC记录

B4571题解

题意简述

维护两个可重集合:单词集合 D、限制集合 R,一共有 m 次操作,分为两类:

  1. add s:把字符串 s 加入单词集合 D
  2. query s x:往限制集合 R 添加一条限制 (s,x)。 限制 (s,x) 的含义:集合 D 中,至少有 x 个字符串,使得 s 是该字符串的前缀。 每次操作结束之后,需要判断限制集合 R 内所有限制是否全部满足。全部满足输出 Yes,否则输出 No。

    核心思路

    维护全局变量 \mathit{bad}:还没有满足的限制总数。\mathit{bad}=0 输出 Yes。 Trie 每个节点:

  1. query s x:走到 s 对应的节点 u
    • 如果 cnt_u \ge x:直接满足,不处理。
    • 否则:x 压入 u 的小根堆,bad++。
  2. 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

以第三次操作为例: 前三次操作完成后,D = \{a, ab\},R = \{(a, 2)\}。 考虑 (a, 2) 限制是否被满足:在集合 D 中的字符串里,a 是 a 的前缀,a 是 ab 的前缀,因此恰好有 2 个字符串满足条件。该限制被满足,所以输出 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;
}