Bzoj P2456 mode___思维

题目大意:

给出 n n n个数 a 1 , a 2 , . . . , a n − 1 , a n a_1,a_2,...,a_{n-1},a_n a1,a2,...,an1,an,保证其中存在一个数 x x x满足在其中出现过的次数大于 ⌊ n 2 ⌋ \left \lfloor \frac{n}{2} \right \rfloor 2n,求最后的 x x x是多少。

n &lt; = 500000 n&lt;=500000 n<=500000
a i &lt; = m a x l o n g i n t a_i&lt;=maxlongint ai<=maxlongint

分析:

我们可以 O ( N ) O(N) O(N)的扫一遍,
每次保留一个数以及其的当前出现次数,如果过程中有一个数与其不同,则给这个数的当前出现次数 − 1 -1 1,否则 + 1 +1 +1
当当前出现次数为 0 0 0的时候,则替换掉,
因为满足 x x x出现的次数大于 ⌊ n 2 ⌋ \left \lfloor \frac{n}{2} \right \rfloor 2n,那么它的出现次数必定大于其他数字的出现次数之和,就有绝对的优势保留下来

因为内存吃的紧, C + + C++ C++开了 i o s t r e a m iostream iostream好像会炸。。

代码:

#include <cstdio>
 
using namespace std;
 
int n, x, now, total;
 
void read(int &x)
{
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9')   { if (s == '-')   f = -1; s = getchar(); }
    while (s >= '0' && s <= '9') { x = x * 10 + (s - '0'); s = getchar(); }
    x = x * f;  
}
 
int main()
{
    read(n);
    read(now); total = 1;
    for (int i = 2; i <= n; i++)
    {
        read(x);
        if (x == now) ++total; else --total;
        if (!total) now = x, total = 1;
    }
    printf("%d\n", now);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值