P11139 [APC001] D - Array Again 题解
原题目:P11139 [APC001] D - Array Again
1. 题目大意
维护一个数列,需要支持下列四种操作:
- 向数列中插入
y 个数x 。 - 向数列中删除
y 个数x (多余次数忽略)。 - 对数列去重。
- 查询
x 的个数。
2. 思路
查询操作仅仅查询 long long 类型的话,仅仅这一个数组就已经占用了 map。
使用 map 需要引入头文件 <map>,map 中存储的每个元素都是一个键值对,即一个值与其对应的关键字(类似下标),这里的值与关键字可以是任何类型,包括自定义的结构体,但关键字必须支持比较操作。在这道题中,我们可以使用 map 来存储每个数出现了几次,这样避免了浪费,空间复杂度由 map 中对应下标的值来实现。
接下来实现操作 3,去重,我认为去重是这道题最难的部分。如果暴力枚举 map 中的每个元素,将不为 map 中的每个元素,记录一个数
7
1 5 2
1 4 3
3
1 5 5
3
4 4
4 5
前两步向数列中添加了 map 中
1
1
在具体实现的时候,我们可以定义一个结构体来作为 map 的结构类型,结构体中含有两个数
注意:只有数列中原来有这个数的时候,才可以将该数的
十年 OI 一场空,不开 long long 见祖宗
3. AC 代码
AC 记录
代码中的
#include<iostream>
#include<cmath>
#include<algorithm>
#include<map>
#define int unsigned long long
using namespace std;
struct Number
{
int num, cnt = 0;
};
const int MAXQ = 1e5+5;
map<int, Number> a;
int op, x, y, q, tot = 0;
void solve(int op)
{
if(op == 1)
{
cin >> x >> y;
if(a[x].cnt < tot)
{
if(a[x].num != 0)
{
a[x].num = 1;
}
a[x].cnt = tot;
}
a[x].num += y;
}
else if(op == 2)
{
cin >> x >> y;
if(a[x].cnt < tot)
{
if(a[x].num != 0)
{
a[x].num = 1;
}
a[x].cnt = tot;
}
if(a[x].num >= y) a[x].num -= y;
else a[x].num = 0;
}
else if(op == 3)
{
tot++;
}
else if(op == 4)
{
cin >> x;
if(a[x].cnt < tot)
{
if(a[x].num != 0)
{
a[x].num = 1;
}
a[x].cnt = tot;
}
cout << a[x].num << '\n';
}
return;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> q;
while(q--)
{
cin >> op;
solve(op);
}
cout << endl;
return 0;
}
题解中的错误欢迎指正,不要直接抄袭代码,小心棕名。