主元素问题--蒙特卡罗

#include "iostream"
#include "ctime"
#include "cmath"
#include "random.h"  //自己编写的头文件

using namespace std;

int key;

template<class Type>
bool majority(Type T[], int n)  //判断主元素的蒙特卡洛方法
{
    int i;
    RandomNumber rnd;
    int index = rnd.Random(n);  //产生0--n-1的下标
    key = T[index];
    int count = 0;
    for(i=0; i<n; i++)
        if(key == T[i])
            count++;
    return count / n > 0.5;
}

//重复调用count次蒙特卡罗方法
template<class Type>
bool major(Type T[], int n, double e, double p) //可使算法的错误概率小于e, p为得到正确解的概率,0.5<p<1
{
    int count = (int)ceil( log(e) / log(p) ); 
    for(int i=1; i<=count; i++)
        if(majority(T, n))
            return true;
    return false;
}

int main() 
{
    int a[] = {5, 5, 5, 5, 5, 5, 1, 3, 4, 6};
    if(major(a, 4, 0.01, 0.6))
        cout << "存在主元素: " << key << endl;
    else
        cout << "不存在主元素!\n";
    return 0;
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值