跳到正文

题解

solution - AT_abc366_c

littlebug约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年8月12日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟

版本

  1. v1当前

Solution

题目要求维护一个数据结构,支持插入元素、删除元素和查询不同元素个数,于是我们可以用 STL 里的 map,或者 unordered_map,推荐使用 unordered_map,因为它底层的实现是一个哈希表,所以操作是 O(1)O(1) 的,而 map 是 O(log⁡n)O(\log n) 的。不过 map 和 unordered_map 的操作都是一样的。

然后分析题目,设我们开了一个 map <int,int> a。对于操作 1,21,2,分别让 a[x] 加一减一;然后对于操作 33,记录一个 tottot 表示个数,每次在操作 11 之前 a[x]==0 时加一,在操作 22 之后 a[x]==0 时减一,tottot 即为操作 33 的答案。注意这里不能直接使用 a.size(),因为即使 a[x]==0,它也是在 a 中占有位置的。

Code

C++
#include<iostream>
#include<cstdio>
#include<unordered_map>
//#define int long long
using namespace std;

int q,sum;
unordered_map <int,int> a;

signed main()
{
	ios::sync_with_stdio(0);
	ios_base::sync_with_stdio(0);
	cin.tie(nullptr);
	cout.tie(nullptr);
	
	cin>>q;
	int op,x;
	while(q--)
	{
		cin>>op;
		if(op==1)
		{
			cin>>x;
			if(!a[x]) ++sum;
			++a[x];
		}
		else if(op==2)
		{
			cin>>x;
			if(a[x]==1) --sum;
			--a[x];
		}
		else cout<<sum<<'\n';
	}
	
	return 0;
}
原文