标准模板库 STL-2 编程题#3:Set(Coursera 程序设计与算法 专项课程3 C++程序设计;执行输入的命令和数据)

来源:互联网 发布:淘宝众筹有什么条件 编辑:程序博客网 时间:2024/04/30 07:40

编程题#3:Set

来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)

注意: 总时间限制: 5000ms 内存限制: 100000kB

描述
现有一整数集(允许有重复元素),初始为空。我们定义如下操作:
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行,每行按要求输出。

样例输入

7add 1add 1ask 1ask 2del 2del 1ask 1

样例输出

121 20 0021 0

提示
Please use STL’s set and multiset to finish the task

程序解答:

#include <iostream>#include <set>#include <string>using namespace std;int main(){    int n;    int a;    string command;    cin >> n;    multiset<int> v;    multiset<int> vsign;    while (n--){        cin >> command >> a;        if (command == "add"){            v.insert(a);            vsign.insert(a);            cout << v.count(a) << endl;        }        else if (command == "ask"){            if (vsign.count(a) > 0)                cout << 1 << " " << v.count(a) << endl;            else                cout << 0 << " " << 0 << endl;        }        else if (command == "del"){            cout << v.erase(a) << endl;  //size_type erase( const key_type &key ); 删除等于key值的所有元素(返回被删除的元素的个数)。        }    }    return 0;}

其他解法参考:
http://blog.csdn.net/nnnnnnnnnnnny/article/details/50526561

阅读全文
0 0
原创粉丝点击