小明和完美序列 C++ 使用set与multiset解决

d34cd0db2526426f82b6ef0241f6b709.png

924710034b2b453ea799045555ca2922.png 

代码如下:

//使用set(不允许重复元素存在相当于map的key)和multiset(允许多个/重复元素存在相当于map的value)

//set用于记录出现了哪些数字;utilset用于装入所有的数字,最后用count计数;

//关于插入补充:map使用insert(插入一对),set使用insert(插入单个)

#include<bits/stdc++.h>

using namespace std;

const int N=1e5+9;

int a[N];

int main()

{

int n;cin>>n;

set<int> myset;

multiset<int> allset;

int deletenumber=0;//用于记录删除的数字个数

for(int i=0;i<n;++i)

{

cin>>a[i];

myset.insert(a[i]);//全部遍历输入,set会自动消去重复数字

allset.insert(a[i]);//全部遍历输入,mutilset会全部装入

}

for(auto x:myset)//使用自动变量遍历set集合

{

int num=allset.count(x);//相当于记录key为x时,对应的value中数字的数量

if(x>num)//如果该数本身大于该数存在的数量

deletenumber+=num;

else if(x<num)//如果该数本身小于该数的数量

deletenumber+=num-x;

}

cout<<deletenumber<<endl;

return 0;

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值