您的位置:首页 > 其它

Hdu 1029 Ignatius and the Princess IV 动态规划

2016-03-11 21:02 351 查看
题意:奇数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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: