【Bzoj2456】mode

Position:


List

Description

  • 给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。

Solution

众数出现的次数>=n/2+1,采用抵消的方法,如果当前数不等于之前记录的数给计数器-1 else +1,当计数器<=0时,可以update数。
证明:对于每一个不是众数的数,它一定会被抵消完。剩下的数众数的个数最多减去前面个数/2,所以个数仍大于剩下的数的1/2。如果当前找到的数的众数,那么接下来它就不会被抵消掉。

Code

// <mode.cpp> - 07/28/16 19:34:21
// This file is made by YJinpeng,created by XuYike's black technology automatically.
// Copyright (C) 2016 ChangJun High School, Inc.
// I don't know what this program is.

#include <cstdio>
using namespace std;
int n,k,ans,now;
int main()
{
    freopen("mode.in","r",stdin);
    freopen("mode.out","w",stdout);
    scanf("%d",&n);
    scanf("%d",&now);
    k=0;ans=now;
    for(int i=2;i<=n;i++){
        scanf("%d",&now);
        if(now==ans)k++;else k--;
        if(k<=0)ans=now,k=1;
    }
    printf("%d",ans);
    return 0;
}
View Code

这里加一个读入输出优化,192MS。提高Rank。
// <mode.cpp> - 07/28/16 19:34:21
// This file is made by YJinpeng,created by XuYike's black technology automatically.
// Copyright (C) 2016 ChangJun High School, Inc.
// I don't know what this program is.
#include <cstdio>
using namespace std;
int n,k,ans,now;
int w;char ch;
inline int getint(){
    ch=getchar();w=0;
    while(ch<'0'||ch>'9')ch=getchar();
    while(ch>='0'&&ch<='9')w=w*10+ch-'0',ch=getchar();
    return w;
}
inline void Plus(int a){
    if(a>=10)Plus(a/10);
    putchar(a%10+'0');
}
int main()
{
    n=getint();now=getint();
    k=0;ans=now;
    for(int i=2;i<=n;i++){
        now=getint();
        if(now==ans)k++;else k--;
        if(k<=0)ans=now,k=1;
    }
    Plus(ans);
    return 0;
}
View Code

 

posted @ 2016-07-30 19:46  _Mashiro  阅读(142)  评论(0编辑  收藏  举报