HDU 1029 Ignatius and the Princess IV

题意:输入n,接着输入n个数,求这群数中至少出现(n+1)/2次的数是哪个。

分析:连续m个数中,如果一个数出现次数超过m/2次,这个数可能是要求的数,如果没有这样的数,重新找一个数。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

 int main()
 {
     int n;
     int ans, x, num;
     while(~scanf("%d", &n))
     {
         num = 1;
         scanf("%d", &ans);
         for(int i=2; i<=n; i++)
         {
             scanf("%d", &x);
             if(x!=ans)
             {
                 num--;
                 if(num<0)
                 {
                     ans = x;
                     num = 1;
                 }
             }
             else
             {
                 num++;
             }
         }
         printf("%d
", ans);
     }

     return 0;
 }
原文地址:https://www.cnblogs.com/mengzhong/p/5352684.html