來源:小白月賽13:小A的彩票
題目描述:
小A最近開始沉迷買彩票,並且希望能夠通過買彩票發家致富。已知購買一張彩票需要3元,而彩票中獎的金額分別爲1,2,3,4元,並且比較獨特的是這個彩票中獎的各種金額都是等可能的。現在小A連續購買了n張彩票,他希望你能夠告訴他至少能夠不虧本的概率是多少。
輸入描述:
一行一個整數N,爲小A購買的彩票數量。
輸出描述:
輸出一個最簡分數a/b,表示小A不虧本的概率。若概率爲1,則輸出1/1,概率爲0,則輸出0/1。
用dp[i][j]表示買第i張彩票,中j元的方案數。那麼
dp[i][j]=dp[i-1][j-1]+dp[i-1][j-2]+dp[i-1][j-3]+dp[i-1][j-4]
邊界條件:
dp[1][1]=1;
dp[1][2]=1;
dp[1][3]=1;
dp[1][4]=1;
很明顯,如果不買,保證不虧。
買了,肯定有可能虧。
因爲只要買了,就有可能全中1元,虧了,也有可能全中4元,穩賺。
所以,只有n==0時,概率爲1/1,概率爲0/1的情況不存在。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 31;
#define ll long long int
ll dp[maxn][maxn*4];
ll power(ll a,ll b )
{
ll r = 1;
ll base = a;
while(b != 0 )
{
if(b & 1)
{
r *= base;
}
base *= base;
b/=2;
}
return r;
}
ll gcd(ll a,ll b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
int main()
{
int n;
while(cin>>n)
{
memset(dp,0,sizeof(dp));
dp[1][1]=1;
dp[1][2]=1;
dp[1][3]=1;
dp[1][4]=1;
for(int i=2;i<=n;++i)
{
for(int j=1;j<=n*4;++j)
{
for(int k=1;k<=4;++k)
{
if(j-k<=0) continue;
dp[i][j]+=dp[i-1][j-k];
}
}
}
// print dp
// for(int i=1;i<=n;++i)
// {
// for(int j=1;j<=n*4;++j)
// {
// cout<<dp[i][j]<<" ";
// }
// cout<<endl;
// }
//
ll ans = 0;
for(int i=1;i<=n*4;++i)
{
if(i>=n*3)
{
ans+=dp[n][i];
}
}
ll a=ans;
ll b=power(4,n);
ll c=gcd(a,b);
if(n==0)
{
cout<<"1/1"<<endl;
}else{
cout<<a/c<<"/"<<b/c<<endl;
}
}
return 0;
}