题意:总共有1-10^9中玩具,每种玩具的价格便是他的序号,现在给出n,m, (1 ≤ n ≤ 100000) and m (1 ≤ m ≤ 10^9),接下来n个数,表示现在他已经拥有的玩具的序号,然后给你m元,问最后还能买多少个玩具(不能买已经拥有的)
思路:
方法一:由于玩具的序号比较大,我们不能用数组来存下,而一开始拥有的玩具数又较少,所以我们可以用map来表示一开始他拥有哪些玩具
又因为他的钱只有10^9,所以买的玩具的最大数目一定不会超过10^6,(因为1+2+...+10^6远远大于10^9),所以只需要暴力枚举1-10^6的玩具,直到钱用完。
时间复杂度为10^6*log n
方法二:
对原来给出的玩具进行排序,贪心取即可(即如果现在的i和a[j]相等,i++,j++),如果不相等,就表示可以买i。
方法一的代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=1100000;
map<int,int>mp;
int ans[maxn];
int main(){
int n,m,x;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&x);
mp[x]=1;
}
int tot=0;
for(int i=1;i;i++){
if(mp[i]==1)
continue;
if(m<i)
break;
m-=i;
ans[++tot]=i;
}
printf("%d\n",tot);
for(int i=1;i<=tot;i++){
if(i==tot)
printf("%d\n",ans[tot]);
else
printf("%d ",ans[i]);
}
}