Set
描述
现有一整数集(允许有重复元素),初始为空。我们定义如下操作:
add x 把x加入集合
del x 把集合中所有与x相等的元素删除
ask x 对集合中元素x的情况询问
对每种操作,我们要求进行如下输出。
add 输出操作后集合中x的个数
del 输出操作前集合中x的个数
ask 先输出0或1表示x是否曾被加入集合(0表示不曾加入),再输出当前集合中x的个数,中间用空格格开。
输入
第一行是一个整数n,表示命令数。0<=n<=100000。后面n行命令,如Description中所述。
输出
共n行,每行按要求输出。
输入样例 1
7
add 1
add 1
ask 1
ask 2
del 2
del 1
ask 1
输出样例 1
1
2
1 2
0 0
0
2
1 0
提示
Please use STL’s set and multiset to finish the task
问题分析
根据提示及题目要求,我们需要建立一个multiset(允许有重复元素)来储存题目所给的整数集。另外,由于操作ask需要输出0或1表示x是否曾被加入集合(0表示不曾加入),因此另外建立一个set储存出现过的元素。
std::multiset<int> B;
std::set<int> C;
之后根据输入的字符串来运行相应的操作,这里参考了C++ 根据字符串 调用同名函数这篇博客,选择使用map来建立操作名与对应函数的关系。
typedef void (*fun)(int);
std::map<string,fun> A;
void buildmap()
{
A["add"]=&add;
A["del"]=&del;
A["ask"]=&ask;
}
然后再根据题目要求编写好每个操作对应的函数即可。
void add(int x)
{
B.insert(x);
C.insert(x);
cout<<B.count(x)<<endl;
}
void del(int x)
{
cout<<B.count(x)<<endl;
while(true)
{
if(B.find(x)==B.end())
break;
else
B.erase(B.find(x));
}
}
void ask(int x)
{
if(C.find(x)==C.end())
cout<<"0"<<" ";
else
cout<<"1"<<" ";
cout<<B.count(x)<<endl;
}
值得注意的是buildmap()应该放在三个操作函数后面,不然会出现函数未定义的错误。
最后附上源码:
#include <iostream>
#include <cstring>
#include <set>
#include <map>
using namespace std;
typedef void (*fun)(int);
std::multiset<int> B;
std::map<string,fun> A;
std::set<int> C;
void add(int x)
{
B.insert(x);
C.insert(x);
cout<<B.count(x)<<endl;
}
void del(int x)
{
cout<<B.count(x)<<endl;
while(true)
{
if(B.find(x)==B.end())
break;
else
B.erase(B.find(x));
}
}