您的位置:首页 > 其它

hdu 1029 Ignatius and the Princess IV

2016-02-15 22:06 411 查看
题意:n个数字中找出出现次数至少为(n+1)/2的数。

方法一:

#include <stdio.h>
#include <string.h>

int A[1000000];

int main()
{
int n, m, i, ok;
while (scanf("%d", &n) != EOF)
{
memset(A, 0, sizeof(A));
for (i=0; i<n; i++)
{
scanf("%d", &m);
A[m]++;
if (A[m] == (n+1)/2)
ok = m;
}
printf("%d\n", ok);
}
return 0;
}

方法二:

/*
多元素即在数列中出现次数多于n/2的元素

我们很容易的看出来,在一个序列中如果去掉2个不同的元素,
那么原序列中的多元素,在新的序列中还是多元素,
因此我们只要按照序列依次扫描,先把t赋值给result,
增加个计数器,cnt = 1;然后向右扫描,
如果跟result相同,则cnt++,不同,那么cnt --,
这个真是我们从上面那个结论里得出的,一旦cnt == 0了,
那么必定c不是多元素,这个时候把t赋值为result,cnt = 1;,
重复该过程,知道结束,这个时候,result就是多元素,
这个的时间复杂度为n,该题本来可以用数组保存每个元素,
然后递归上述过程,可是,用数组超内存,
因此我们可以直接按照上述过程计算

*/

//用cin,cout会超时
#include<iostream>
#include<string.h>
using namespace std;

int main()
{
int n,i;
int t;
int cnt;
int result;
while(scanf("%d",&n)!=EOF)
{
cnt=0;
for(i=0;i<n;i++)
{
scanf("%d",&t);

if(cnt==0)
{
cnt=1;
result=t;
}
else
{
if(t==result)cnt++;
else cnt--;
}

}
printf("%d\n",result);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: