【luogu P2397 yyy loves Maths VI (mode) 】 题解

题目链接: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;
}
posted @ 2018-07-26 17:18  Misaka_Azusa  阅读(127)  评论(0编辑  收藏  举报
Live2D