BZOJ 2456 Mode

【题意概述】

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

【题解】

  看起来很水。。然而内存限制只有1M

  所以要用一点小技巧

  因为众数出现的次数超过n/2,所以我们可以把每个数和不一样的数抵消,最后剩下的数一定就是众数

  我们用cnt记录目前的众数出现的次数,当目前的众数与读入的数不一样时,将它们抵消;即cnt--;一样时cnt++

  当cnt=0时我们把当前的数看作众数

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 int n,x,cnt,now;
 5 void read(int &k){
 6     k=0; int f=1; char c=getchar();
 7     while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
 8     while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar();
 9     k*=f;
10 }
11 int main(){
12     read(n);
13     while(n--){
14         read(x);
15         if(cnt==0) now=x;
16         cnt+=x==now?1:-1;
17     }
18     return printf("%d\n",now),0;
19 }
View Code

 

posted @ 2017-12-11 19:07  Driver_Lao  阅读(145)  评论(0编辑  收藏  举报