[BZOJ2456]Mode-栈思想

来源:互联网 发布:java安装在d盘教程 编辑:程序博客网 时间:2024/06/05 09:44

说在前面

这道题解法真的好巧!
想了很久最后写了一个随机化算法,然后WA掉了QAQ


题目

给一串长度为N的数列,其中有一个数字的出现次数超过了N/2次,输出这个数。

空间限制:1MB


解法

使用栈的思想,当两个数字不同的时候就抵消掉他们,最后剩下的数字就是所求。实现的时候不是真的用栈,而是用两个变量,一个记录当前数字是多少,另一个记录当前数字出现次数

自带大常数的代码

(前半部分是我的随机化算法hhhhh)

/*#include <cstdio>#include <cstring>#include <algorithm>using namespace std ;int num[20000] , cnt[20000] , topp , N , xt , i , j , a , maxcnt ;int main(){    scanf( "%d" , &N ) ;    xt = N / 30 + 1 ;    for( i = 1 ; i <= N ; i ++ ){        scanf( "%d" , &a ) ;        if( N%xt == 0 ){            for( j = 1 ; j <= topp ; j ++ )                if( num[j] == a ){ cnt[j] ++ ; break ; }            if( j == topp + 1 ){                num[++topp] = a ;                cnt[topp] = 1 ;                //printf( "%d " , a ) ;            }        }    }    for( int i = 1 ; i <= topp ; i ++ )        maxcnt = max( maxcnt , cnt[i] ) ;    for( int i = 1 ; i <= topp ; i ++ )        if( cnt[i] == maxcnt ){            printf( "%d" , num[i] ) ;            return 0 ;        }}*/#include <cstdio>#include <cstring>#include <algorithm>using namespace std ;int a , num , cnt , N ;int main(){    scanf( "%d" , &N ) ;    for( int i = 1 ; i <= N ; i ++ ){        scanf( "%d" , &a ) ;        if( !cnt ) num = a , cnt = 1 ;        else if( a == num ) cnt ++ ;        else if( cnt == 1 ) cnt = 0 , num = 0 ;        else cnt -- ;    }    printf( "%d" , num ) ;}