HDU 1029 Ignatius and the Princess IV (思路)

本文介绍了一种高效算法,用于从含有奇数个元素的序列中找出出现次数超过(N+1)/2的元素。该算法通过遍历序列并使用计数器跟踪当前候选众数的方式实现。

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1029

大意:从一个N元素的序列(N为奇数)中找出出现次数大于(N+1)/ 2 的元素。

思路:设答案为result。按照序列依次扫描,先把数组中第一个元素赋值给result,增加个计数器,cnt = 1;然后向右扫描,如果跟result相同,则cnt++,不同,那么cnt --。当cnt为0时,result换为当前的数。最后的result即为答案。

#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#define fin(a) freopen("a.txt","r",stdin)
#define fout(a) freopen("a.txt","w",stdout)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long LL;
using namespace std;
const int maxn = 1e6 + 10;
int result, cnt;

int main() {
  int n, x;
  while(scanf("%d", &n) == 1) {
    cnt = 0;
    while(n--) {
      scanf("%d", &x);
      if(cnt == 0) {
        result = x;
        cnt = 1;
      }
      else if(result == x) cnt++;
      else cnt--;
    }
    printf("%d\n", result);
  }
  return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值