bzoj 2456 mode 题解

来源:互联网 发布:mac换行按键 编辑:程序博客网 时间:2024/04/28 00:37

转载请注明:http://blog.csdn.net/jiangshibiao/article/details/21648893

【题目】

2456: mode

Time Limit: 1 Sec  Memory Limit: 1 MB
Submit: 628  Solved: 289
[Submit][Status]

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


【分析】第一次看到这道题觉得太神了!因为内存限制只有1MB,即只能开几个变量而已!难道是那种有关xor的题目?但这是找众数,根本不可能。在RZZ大神的指点下,我用了一种很神奇的方法,详见代码。

【代码】

/**************************************************************    Problem: 2456    User: jiangshibiao    Language: C++    Result: Accepted    Time:364 ms    Memory:804 kb****************************************************************/ #include<cstdio>using namespace std;int n,a,tot,now;int main(){  scanf("%d",&n);  while (n)  {    n--;    scanf("%d",&a);    if (now==a) tot++;    else    {      tot--;      if (tot<=0) {tot=1;now=a;}    }  }  printf("%d",now);  return 0;}

【回头】觉得不可思议?觉得有反例。这么想:假设众数是3,且你想卡掉这个程序。如果把3放在前面:3,3,3,2,2.那么3的个数会积累起来,不会被2消掉。放后面:2,3,4,3,3,1,3,5,3.这样最后一个3就会保留。所以算法正确。

6 1