题解:P18018 [GCPC 2026] Fighting Fraud

· · 题解

前置知识:字典树。

使用两个 cnt 数组来记录该字符串还没有送出的个数和该字符串取的次数即可。

#include <bits/stdc++.h>
using namespace std;
const int N=1e6+5;
int n, cnt[N], cnt2[N], k[30][N], tot;
bool insert(string s, int op){
    // 用op把两个函数写成一个函数比较方便
    int q = 0;
    for(int i = 0;i < s.size();i++){
        int x = s[i] - 'a';
        if(k[x][q] == 0){
            tot ++;
            k[x][q] = tot;
        }
        q = k[x][q];
    }
    cnt[q] += op;
    cnt2[q] ++;
    if(cnt[q] < 0 || cnt2[q] > 2){
        return 1;
    }
    return 0;
}
int main(){
    cin >> n;
    while(n--){
        string op, a;
        cin >> op >> a;
        if(op=="pickup"){
            if(insert(a, 1)){
                cout << "no";
                return 0;
            }
        }
        else {
            if(insert(a, -1)){
                cout << "no";
                return 0;
            }
        }
    }
    for(int i = 1;i <= tot;i++){
        if(cnt[i]){// 判断是否还有剩余
            cout << "no";
            return 0;
        }
    }
    cout << "yes";
    return 0;
}