北大程序設計與算法(三)測驗題彙總(2020春季)
描述
現有一整數集(允許有重複元素),初始爲空。我們定義如下操作:
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行,每行按要求輸出。
樣例輸入
7
add 1
add 1
ask 1
ask 2
del 2
del 1
ask 1
樣例輸出
1
2
1 2
0 0
0
2
1 0
提示
Please use STL’s set and multiset to finish the task
分析
set模板的使用
#include <set>
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
multiset<int> sets;
set<int> be_sets;
int n;
cin >> n;
char cmd[20];
int num;
set<int>::iterator li;
while (n--) {
cin >> cmd;
int count = 0;
switch (cmd[1]) {
case 'd':
cin >> num;
sets.insert(num);
be_sets.insert(num);
cout << sets.count(num) << endl;
break;
case 'e':
cin >> num;
cout << sets.count(num) << endl;
for (li = sets.begin(); li != sets.end(); li++){
if (*li == num){
sets.erase(li);
}
}
break;
case 's':
cin >> num;
if (be_sets.find(num) != be_sets.end()) {
cout << 1 << " " << sets.count(num) << endl;
}
else
cout << 0 << " " << sets.count(num) << endl;
break;
}
}
return 0;
}