[ABC366C] Balls and Bag Query 题解

[ABC366C] Balls and Bag Query 题解

题目传送门

AT原题传送门

首先是题面的翻译:

你有一个袋子,给予 \(Q\) 次操作,操作有三种

  • 1 \(x\) ,将一个 写有整数 \(x\) 的球放入袋中。
  • 2 \(x\) ,从袋中取出一个写有整数 \(x\) 的球。
  • 3 ,查询袋中球上的不同整数的数目。

整理了一下思路,发现此题并不难。

由于 \(x\) 的数据范围较小,可以使用计数排序的思想,使 \(a[x]\) 的值代表 \(x\) 在袋子中的个数。则这题的难度将大幅缩减,三操作简化为统计共有多少个非零的 \(a[i]\)

AC code:

#include <bits/stdc++.h>
#define seq(q, w, e) for (int q = w; q <= e; q++)
#define ll long long
using namespace std;
const int maxn = 2e6+10;
int a[maxn];
int n,op,sum,tot;
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin>>n;
    seq(i,1,n){
        cin>>op;             //操作
        if(op==1){
            cin>>sum;
            if(!a[sum]){     //如果a[sum]之前是0,现在非零,更新tot
                tot++;
            }
            a[sum]++;
        }
        if(op==2){
            cin>>sum;
            a[sum]--;
            if(!a[sum]){    //若更新后,a[i]归零,更新tot
                tot--;
            }
        }
        if(op==3){
            cout<<tot<<endl;
        }
    }
    return 0;
}
posted @ 2024-08-12 09:25  adsd45666  阅读(14)  评论(0编辑  收藏  举报