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\n", 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\n", a.a[0][0]%mod); } } return 0; }