Batting Practice LightOJ - 1408(概率dp)
题意:有无限个球,进球的概率为p,问你连续不进k1个球或者连续进k2个球需要使用的球的个数的期望
思路:
\(定义f[i]表示已经连续不进i个球,还需要连续不进k1-i个球的期望\)
\(g[i]表示已经连续进了i个,还需要连续进k2-i个球的期望\)
显然\(f[k1] = g[k2] = 0\)
\(任意0<=i<k1有f[i] = (1-p) \cdot f[i+1] + p \cdot g[1] + 1\)
\(任意0<=i<k2有g[i] = (1-p) \cdot f[1] + p \cdot g[i+1] + 1\)
不好解的样子,列矩阵高斯消元一发,WA,把eps从1e-6改到1e-15还是过不了,用long double交,时限卡的紧,TLE
搜了一发题解,原来上面那个式子可以直接求通项,依次回代就可以求出f[0]和g[0]了
#include<bits/stdc++.h>
#define LL long long
#define P pair<int,int>
using namespace std;
const double eps = 1e-6;
double a[60][60];
int gauss(int n,int m){
int col,i,mxr,j,row;
for(row=col=0;row<=n&&col<=m;row++,col++){
mxr = row;
for(i=row+1;i<=n;i++)
if(fabs(a[i][col])>fabs(a[mxr][col]))
mxr = i;
if(mxr != row) swap(a[row],a[mxr]);
if(fabs(a[row][col]) < eps){
row--;
continue;
}
for(i=0;i<=n;i++)///消成上三角矩阵
if(i!=row&&fabs(a[i][col])>eps)
for(j=m;j>=col;j--)
a[i][j]-=a[row][j]/a[row][col]*a[i][col];
}
row--;
for(int i = row;i>=0;i--){///回代成对角矩阵
for(int j = i + 1;j <= row;j++){
a[i][m] -= a[j][m] * a[i][j];
}
a[i][m] /= a[i][i];
}
return row;
}
int main()
{
int T;
int cas = 1;
cin>>T;
while(T--)
{
int k1,k2;
double p;
scanf("%lf%d%d",&p,&k1,&k2);
printf("Case %d: ",cas++);
/*
memset(a,0,sizeof(a));
int col = k1 + k2 + 2;
for(int i = 0;i < k1;i++){
a[i][i] = 1;
a[i][i+1] = p - 1;
a[i][k1+2] = -p;
a[i][col] = 1;
}
a[k1][k1] = 1,a[k1][col] = 0;
for(int i = 0;i < k2;i++){
a[k1+1+i][k1+1+i] = 1;
a[k1+1+i][k1+1+i+1] = -p;
a[k1+1+i][1] = p - 1;
a[k1+1+i][col] = 1;
}
a[k1+k2+1][k1+k2+1] = 1,a[k1+k2+1][col] = 0;
int row = gauss(k1+k2+1,k1+k2+2);
printf("%.6f\n",a[0][col]);
*/
if(p < eps) printf("%.6f\n",1.0 * k1);
else if(1 - p < eps) printf("%.6f\n",1.0 * k2);
else{
double q;
q=1-p;
double a1=1-pow(q,k1-1),b1=a1/(1-q);
double a2=1-pow(p,k2-1),b2=a2/(1-p);
double t1=(a1*b2+b1)/(1-a1*a2),f1=a2*t1+b2;
printf("%.6f\n",p*f1+q*t1+1);
}
}
return 0;
}