[洛谷P2397]yyy loves Maths VI (mode)

题目大意:给你一堆数,他们的众数出现次数超过了一半,求这个众数。

解题思路:首先这题空间只有3.5M,开数组存根本存不下。而且此题scanf能过,读入优化却被卡了!!

由于众数次数出现了一半,那么我们把众数和其他数抵消,最后至少还剩下1个,那么只要模拟抵消的过程即可。具体过程见代码。

C++ Code:

 

#include<cstdio>
#include<cctype>
int zs=-1,cs=0,x;
int main(){
	int n;
	scanf("%d",&n);
	while(n--){
		scanf("%d",&x);
		if(x==zs)++cs;else --cs;
		if(cs<0)zs=x,cs=1;
	}
	printf("%d\n",zs);
	return 0;
}

 

posted @ 2017-08-08 09:16  Mrsrz  阅读(127)  评论(0编辑  收藏  举报