Hdu 1029 Ignatius and the Princess IV 动态规划

题意:奇数n个数,存在一个数出现的次数大于(n+1)/2次,求这个数;

这个数出现的次数比其他数出现的次数加起来还多,那么当这个数出现时+1,其他的数出现时-1,最后得到的数为正数。

假定一个数为特殊数,若当前数与特殊数相同则cnt++,若不相同则cnt--,如果这时cnt<0,用当前数替代特殊的数。不管怎么样,由于特殊数次数大于(n+1)/2次,最终保留的数一定是特殊数。

#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>

using namespace std;

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int cnt=0,t,ans;
        while(n--)
        {
            scanf("%d",&t);
            if(ans==t)  cnt++;
            else if(--cnt<0) cnt=0,ans=t;
        }
        cout<<ans<<endl;
    }
}

你可能感兴趣的:(dp,动态规划,C语言,HDU)