牛客网暑假第四场多校赛 G Maximum Mode

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

*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值