BZOJ2456 mode

本文介绍了一种高效查找数组中出现次数超过一半元素的算法。利用两两相消的方法,在仅使用1MB的空间限制下找到众数。代码实现采用C++语言。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思维题

题目传送门

开始以为是SB题,然后发现空间只给1M。。。

因为众数的个数一定 >n/2 > n / 2 ,那么我们就把不相同的数两两相消,剩下的就是众数了。

代码:

#include<cctype>
#include<cstdio>
using namespace std;
int ans,sum;
inline char readc(){
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    return l==r?EOF:*l++;
}
inline int _read(){
    int x=0,f=1; char ch=readc();
    while (!isdigit(ch)) { if (ch=='-') f=-1; ch=readc(); }
    while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x*f;
}
int main(){
    for (int n=_read();n;n--){
        int x=_read();
        if (x==ans) sum++;
        else if (sum) sum--;
        else ans=x,sum++;
    }
    return printf("%d\n",ans),0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值