soj 4389模拟



背景:周赛A题,

学习:1.开始没有注意到题目中对于帖子数大于1/2的描述,纯暴力计数,各种超!

2.后来发现按顺序扫描每一个数看是否有它在数组中的数量大于1/2,是则找到。我的代码:

#include<stdio.h>
#include<string.h>
int str[10000000];
int main(void)
{
	int n;
	scanf("%d",&n);
	while(n--)
	{
		int m,cout=0;
		scanf("%d",&m);
		for(int i=0;i<m;i++)
		{
			scanf("%d",&str[i]);
		}
		for(int i=0;i<m;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(str[j]!=-1){
				   if(str[j]==str[i])
				   {
					    cout++;
				     	if(cout>=m/2+1)
					    {
						printf("%d\n",str[i]);
						goto l1;
				    	}
				   }
			}	
			}
			str[i]=-1;	
			cout=0;
		}
l1:     cout=0;		
	}
	return 0;
} 

3.这样能过但是开了巨大的内存(oj极限是10的8次方个int?)

解题报告给出了比较先进的方法:假定第一个数是并计数count为1,以后遇见和它相同的就count自增一,当count为0时,可以就变为当前读入的数,最后剩下的可以必然是要找的大于1/2的数。给出代码:

#include<stdio.h>
#include<string.h>
int str[10000000];
int main(void)
{
	int n;
	scanf("%d",&n);
	while(n--){ 
		int m,count=0,x,key=-1;
		scanf("%d",&m);
		while(m--){
			scanf("%d",&x);
			if(x!=key) count--;
			else count++;
			if(count<0) {
				key=x;
				count=0;
			}
		}
		printf("%d\n",key);
	} 
	return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值