牛客网算法学习记录-概率

来源:互联网 发布:淘宝透明睡衣买家秀 编辑:程序博客网 时间:2024/05/23 14:23

n只蚂蚁从正n边形的n个定点沿着边移动,速度是相同的,问它们碰头的概率是多少?

给定一个正整数n,请返回一个数组,其中两个元素分别为结果的分子和分母,请化为最简分数。

测试样例:
3
返回:[3,4]
因为是正N边型,所以所有的点的路程相同。他们的速度又是相同的。从总情况来说,一个结点有两种选择,那么N个结点就是 2^N种没有碰头情况则是所有结点同时顺时针,或者逆时针走。
class Ants {public:    vector<int> collision(int n) {        // write code here        int tem = 1;        while(n>0){            tem = tem *2;            n--;        }        int m = tem  - 2;        int t = gcm (tem,m);                vector<int> result;        result.push_back(m/t);        result.push_back(tem/t);        return result;    }        int gcm(int n ,int m){                int temp = n %m;        while(temp!=0){                        n = m;            m = temp;            temp = n%m;                    }                return m;    }};
给定一个等概率随机产生1~5的随机函数,除此之外,不能使用任何额外的随机机制,请实现等概率随机产生1~7的随机函数。(给定一个可调用的Random5::random()方法,可以等概率地随机产生1~5的随机函数)
class Random5 {public:static int randomNumber();};class Random7 {public:    int rand5() {        return Random5::randomNumber();    }    // 以上内容请不要修改        int randomNumber() {        // 代码写这里,通过rand5函数随机产生[1,7]        int num = rand5()-1+5*(rand5()-1);//随机生成0-24        while(num>20){//21-24的概率平均分布到0-20中            num = rand5()-1+5*(rand5()-1);        }        int result = num %7;//随机生成0-6        return result +1;//随机生成1-7            }};
给定一个以p概率产生0,以1-p概率产生1的随机函数RandomP::f(),p是固定的值,但你并不知道是多少。除此之外也不能使用任何额外的随机机制,请用RandomP::f()实现等概率随机产生0和1的随机函数。
我是参考的答案
个人的理解是,将大概率1或者0 的情况通过 A== B 过滤掉,那么剩余的就是等可能概率的那部分
class RandomP {public:static int f();};class Random01 {public:    // 用RandomP::f()实现等概率的01返回    int random01() {        while(true){            int a = RandomP::f();            int b = RandomP::f();            if(a!=b){                return a>b?1:0;            }        }        return 0;    }};
0 0
原创粉丝点击