题目链接:https://www.luogu.org/problemnew/show/P2397
卡空间。
对于众数出现次数 > n/2 我们考虑rand。
每次正确的概率为1/2,五个测试点,全对的概率为1/32。
所以:

#include <ctime>
#include <cstdio> 
#include <cstdlib>
using namespace std;
int n, m;
int main()
{
	scanf("%d",&n);
	srand(time(NULL));
	int r = rand()%n+1;
	for(int i = 1; i <= n; i++)
	{
		scanf("%d",&m);
		if(i == r) 
		{
			printf("%d",m);
			return 0;
		}
	}
}

正解是一个叫做摩尔♂投票法的东西。
先取出一个数。
再按顺序拿出每个数。
如果这两个数不一样,那么我们就都扔掉。
如果这两个数一样,我们就留着一个。
这样到最后一定是众数。
???(我也不知道这样证对不对,xjb证明的)

#include <cstdio>
using namespace std;
int ans, cnt, n, now;
int main()
{
    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%d",&now);
        if(ans == now) cnt++;
        if(cnt == 0)
        {
            ans = now; cnt++;
        }
        if(ans != now) cnt--;
    }
    printf("%d",ans);
    return 0;
}

相关文章:

  • 2021-10-25
  • 2022-02-04
  • 2022-02-13
  • 2021-09-14
  • 2021-05-31
  • 2022-03-03
  • 2021-09-12
猜你喜欢
  • 2021-07-14
  • 2022-02-28
  • 2022-12-23
  • 2022-02-23
  • 2022-02-18
  • 2022-12-23
相关资源
相似解决方案