试题E:爬树的甲壳虫

解析:

涉及知识点:

[1]知识点:乘法逆元_空城老祖的博客-CSDN博客

[2]快速幂算法_空城老祖的博客-CSDN博客

假设数的结构如下图所示,且攀爬一层的单位时间为1:

 1、先考虑从第0层到第1层的期望

则期望为: 

令F(x)如下,因为p1<1,故p1的无穷大次方为0

 所以E(x=1) = (1-p_1)\frac{1}{(1-p_1)^2}=\frac{1}{1-p_1}

2、再考虑第n-1层到n层的期望

 同理,E(x=n)=(E(x=n-1)+1)\times \frac{1}{1-p_n}

结论:

E(n)=(E(n-1)+1)\times \frac{1}{1-p_n}=(E(n-1)+1)\times \frac{1}{1-\frac{x_i}{y_i}}=(E(n-1)+1)+\frac{y_i}{y_i-x_i}

3、计算

E(n)%p = (E(n-1)+1)%p+\frac{y_i}{y_i-x_i}%p=(E(n-1)+1)%p+y_i%p \times (y_i-x_i)_{inv}%p

其中(y_i-x_i)_{inv}=y_i^{p-2}

4、代码实现

细节:注意%p*y与*y%p之间的差别

public class ExaminationF {
    final static Long p = 998244353L;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int high = scanner.nextInt();
        Long res = 0L;
        for(int i=0;i<high;i++){
            Long x = scanner.nextLong();
            Long y = scanner.nextLong();
            //如果写成%p*y就会出错
            res = (res+1)*y%p* MathUtils.quickPow(y-x,p-2,p)%p;
            //res = (res+p)%p;
        }
        System.out.println(res);
    }
}
    public static Long quickPow(Long a,Long n,Long p){
        //结果
        Long res = 1L;
        while (n != 0) {
            //判断 n 的二进制的最后一位是否为0
            if((n&1)!=0){
                //当n的二进制最后一位为1时,乘以当前的权重
                res = (res*a)%p;
            }
            //更新n,每次n向右移一位
            n = n >> 1;
            //更新每一位的权重
            a = (a*a)%p;
        }
        return res;
    }

完整代码

import java.util.Scanner;

public class Main {

    public static Long quickPow(Long a,Long n,Long p){
        //结果
        Long res = 1L;
        while (n != 0) {
            //判断 n 的二进制的最后一位是否为0
            if((n&1L)!=0){
                //当n的二进制最后一位为1时,乘以当前的权重
                res = (res*a)%p;
            }
            //更新每一位的权重
            a = (a*a)%p;
            //更新n,每次n向右移一位
            n = n >> 1;
        }
        return res;
    }
    public static void main(String[] args) {

        Long p = 998244353L;
        Scanner scanner = new Scanner(System.in);
        int high = scanner.nextInt();
        Long res = 0L;
        for(int i=0;i<high;i++){
            Long x = scanner.nextLong();
            Long y = scanner.nextLong();

            res = (res+1L)*y%p*quickPow(y-x,p-2L,p)%p;
            res = (res+p)%p;
        }
        System.out.println(res);
    }
}

参考资料

2022第13届蓝桥杯c/c++A组E题爬树的甲壳虫【概率期望+乘法逆元】_冷风的呼啸的博客-CSDN博客

测试OJ

题目详情 - [蓝桥杯2022初赛] 爬树的甲壳虫 - ZHOJ

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值