G Maximum Mode
题 意:给你n个数字,可以删除m个数字。求删除m个数字之后,使得众数最大。
数据范围:
1<=n<=1e5
0<=m<=n
输入样例:
链接:https://www.nowcoder.com/acm/contest/142/G
来源:牛客网
5
5 0
2 2 3 3 4
5 1
2 2 3 3 4
5 2
2 2 3 3 4
5 3
2 2 3 3 4
5 4
2 2 3 3 4
输出样例:
-1
3
3
3
4
思 路:目标是为了找到删除m个之后最大的众数,开始,想的是二分,发现二分不具有单调性。尝试一下贪心,按每个数字出现的次数排序,出现次序相同肯定优先选择后面一个。出现次数多的是最有可能的。
收 获:学习了一个新的思想。拓展了思维
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
map<int,int> mp;
struct node{
int val;
int t;
}a[maxn];
int n,m;
bool cmp(node x,node y){
if(x.t > y.t) return true;
else if(x.t == y.t && x.val < y.val)return true;
else return false;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
mp.clear();
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
int temp;
scanf("%d",&temp);
mp[temp]++;
}
map<int,int>::iterator it;
int k=0;
for(it=mp.begin();it!=mp.end();it++){
a[k].val = it->first;
a[k++].t = it->second;
}
sort(a,a+k,cmp);
int sum = 0;
bool flag = true;
int ans = 0;
for(int i=0;i<k;i++){
if(i!=k-1 &&a[i].t == a[i+1].t ){
sum+=a[i].t;
continue;
}else{
if(flag){
if(sum-m <= i*(a[i].t-1)){
ans = max(ans,a[i].val);
flag = false;
}
}else if(a[i].val > ans){
if(sum - m <= i*(a[i].t-1)){
ans = a[i].val;
}
}
sum+=a[i].t;
}
}
if(flag) printf("-1\n");
else printf("%d\n",ans);
}
return 0;
}
/*
5
5 0
2 2 3 3 4
5 1
2 2 3 3 4
5 2
2 2 3 3 4
5 3
2 2 3 3 4
5 4
2 2 3 3 4
*/