hdu 1029 Ignatius and the Princess IV

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值