zoukankan      html  css  js  c++  java
  • 2017 ACM-ICPC 亚洲区(西安赛区)网络赛 Coin 概率+矩阵快速幂

    题目链接:

    https://nanti.jisuanke.com/t/17115

    题意:

    询问硬币K次,正面朝上次数为偶数。

    思路:

    dp[i][0] = 下* dp[i-1][0] + 上*dp[i-1][1] (满足条件的)

    dp[i][1]= 上*dp[i-1][0] + 下*dp[i-1][1] (不满足条件的)

    矩阵优化这个DP

    #include <bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const LL mod = 1e9+7;
    struct Matrix{
        LL a[2][2];
        void set1(){
            memset(a, 0, sizeof(a));
        }
        void set2(){
            set1();
            for(int i=0; i<2; i++) a[i][i]=1;
        }
    };
    Matrix operator*(const Matrix &a, const Matrix &b){
        Matrix res;
        res.set1();
        for(int i=0; i<2; i++){
            for(int j=0; j<2; j++){
                for(int k=0; k<2; k++){
                    res.a[i][j] = (res.a[i][j] + a.a[i][k]*b.a[k][j]%mod)%mod;
                }
            }
        }
        return res;
    }
    Matrix qsm(Matrix a, LL n){
        Matrix res;
        res.set2();
        while(n){
            if(n&1) res = res*a;
            a = a*a;
            n /= 2;
        }
        return res;
    }
    LL qsmrev(LL a, LL n){
        LL ret = 1;
        while(n){
            if(n&1) ret=ret*a%mod;
            a=a*a%mod;
            n/=2;
        }
        return ret;
    }
    
    int main()
    {
        int T;
        scanf("%d", &T);
        while(T--){
            LL p, q, k;
            scanf("%lld %lld %lld", &p,&q,&k);
            LL up = q*qsmrev(p, mod-2)%mod;
            LL down = (p-q)*qsmrev(p, mod-2)%mod;
            Matrix a, b;
            a.set1();
            a.a[0][0]=down;
            a.a[1][0]=up;
            if(k==1){
                printf("%lld
    ", a.a[0][0]);
            }
            else{
                b.a[0][0]=down, b.a[0][1]=up;
                b.a[1][0]=up, b.a[1][1]=down;
                a = qsm(b, k-1)*a;
                printf("%lld
    ", a.a[0][0]%mod);
            }
        }
        return 0;
    }
    
  • 相关阅读:
    无密码登录Linux
    php生成压缩包
    验证数字的正则表达式集
    初识MEF
    实现Linq.Distinct方法
    《Windows Internal》(2)
    《Windows Internals》(1)
    使用MEF宿主在一个应用程序上
    mysql错误记录集合
    python基本知识之数据类型
  • 原文地址:https://www.cnblogs.com/spfa/p/7532958.html
Copyright © 2011-2022 走看看