Ignatius and the Princess IV
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1029
解题思路:
题目要求一个数至少出现(n+1)/2次。用cnt来记录解出现的次数,出现了正确解就令cnt自增1,不是正确解就使cnt自减1。
那么,正确解对应的cnt一定是不小于1的。可以用一个极端的例子来说明下:输入3 3 3 3 3 3 2 1 5 6 8,开始当ans=3时,cnt=6,
那么继续执行num!=3了,cnt开始自减,但最终cnt=1,始终不会进入程序if(cnt==0){}内部执行了。
利用最终的cnt,还可以计算出解出现的次数。
AC代码:
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
while(~scanf("%d",&n)){
int x,ans,cnt = 0;
while(n--){
scanf("%d",&x);
if(cnt == 0){
ans = x;
cnt++;
}else{
if(x == ans)
cnt++;
else
cnt--;
}
}
printf("%d\n",ans);
}
return 0;
}