064:Set 程序设计实习MOOC / 程序设计与算法(一)测验题汇总(2020春季)

064:Set
总时间限制: 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行,每行按要求输出。

样例输入

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

At the beginning, I didn’t see STL, so I just used the normal way to solve this question.

#include <iostream>
using namespace std;

void replace(int x, int n, int a[]){
   int sum = 0;
   for(int i = 0; i <= n - 1; ++ i){
      if(a[i] == x){
         sum = sum + 1;
         a[i] = NULL;
      }
   }
   cout << sum << endl;
}

int fun(int x, int n, int a[]){
   int sum = 0;
   for(int i = 0; i <= n; ++ i){
      if(a[i] == x)
         sum = sum + 1;
   }
   return sum;
}


int main(){
   int a[100], b[100];
   string s;
   int n, x;
   cin >> n;
   int i = 0;
   while(n--){
      cin >> s;
      switch(s[1]) {
         //add
         case 'd':
            cin >> x;
            a[i] = x;
            b[i] = x;
            cout << fun(x, i, a) << endl;
            i = i + 1;
            break;
         //del
         case 'e':
            cin >> x;
            replace(x, i, a);
            break;
         //ask
         case 's':
            cin >> x;
            if(fun(x, i, b))
               cout << "1 " << fun(x, i, a) << endl;
            else
               cout << "0 " << fun(x, i, a) << endl;
            break;
         default:
            cin >> s;
            break;
      }
   }
   return 0;
}

I USED STL HERE!!!

#include<iostream>
#include<string>
#include<set>
using namespace std;

int main(){
   string s;
   multiset<int> st;
   set<int> cpst;
   set<int>::iterator it;
   int n, x;
   cin >> n;
   while(n--){
      cin >> s;
      
      switch (s[1]) {
         //add
         case 'd':
            cin >> x;
            st.insert(x);
            cpst.insert(x);
            cout << st.count(x) << endl;
            break;
         //del
         case 'e':
            cin >> x;
            cout << st.count(x) << endl;
            st.erase(x);
            break;
         case 's':
            cin >> x;
            it = cpst.find(x);
            if(it != cpst.end())
               cout << "1 " << st.count(x) << endl;
            else
               cout << "0 " << st.count(x) << endl;
            break;
         default:
            cin >> s;
            break;
      }
   }
   return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值