码迷,mamicode.com
首页 > 其他好文 > 详细

[BZOJ2456] mode

时间:2016-04-04 06:44:21      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

Description

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

Input

  第1行一个正整数n。
  第2行n个正整数用空格隔开。

Output

    一行一个正整数表示那个众数。

Sample Input

5
3 2 3 1 3

Sample Output

3

HINT

  100%的数据,n<=500000,数列中每个数<=maxlongint。

  zju2132 The Most Frequent Number 

Source

  鸣谢 黄祎程

Solution

  历史总是惊人地相似,被九章算法某一道简单题(题目详见CodeVS3295)艹后又被一道简单题艹。

  1MB空间,连数组都不让开,用cin都MLE。

  要不你先想一会

  。。。。。。

  。。。。。。

  。。。。。。

  。。。。。。

  。。。。。。

  。。。。。。

  想不到吧,蛤蛤。

技术分享
 1 #include <cstdio>
 2 using namespace std;
 3 int main()
 4 {
 5     int n, a, tot = 0, ans = 0;
 6     scanf("%d", &n);
 7     while(n--)
 8     {
 9         scanf("%d", &a);
10         if(a == ans) tot++;
11         else
12         {
13             tot--;
14             if(tot <= 0) ans = a, tot = 1;
15         }
16     }
17     printf("%d", ans);
18     return 0;
19 }
View Code

  tot为正表示这个数目前是众数,tot小于等于0则表示这个数目前不会成为众数。

  如果ans这个数已经出现了超过n/2次,那么它不会被别的数替换了,因为tot会一直大于0。

  如果ans这个数没出现超过n/2次,那么它一定会被其它数替换,且最终会被换成众数。

  MDZZ,语文好差,感觉自己无法给别人讲懂题。

[BZOJ2456] mode

标签:

原文地址:http://www.cnblogs.com/CtrlCV/p/5351290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!