首页 > 代码库 > BZOJ 1867 NOI1999 钉子和小球 动态规划

BZOJ 1867 NOI1999 钉子和小球 动态规划

题目大意:给定一个钉子阵,小球从最上方的钉子释放,求到达最底端某个位置的概率

只需要DP就好了 f[i][j]表示小球落在第i行第j个钉子上的概率

如果一个点有钉子 f[i+1][j]和f[i+1][j+1]平分这个点的概率

如果一个点没有钉子 f[i+2][j+1]得到这个点的全部概率

最后输出f[n+1][m+1]即可 注意不能输出回车 否则PE

无视这凶残的结构体操作符重载吧0.0

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define M 60
using namespace std;
typedef long long ll;
struct fraction{
	ll numerator,denominator;
	fraction(ll _=0,ll __=1):numerator(_),denominator(__){}
}f[M][M];
ll GCD(ll x,ll y)
{
	return y?GCD(y,x%y):x;
}
void Reduction(fraction &x)
{
	ll gcd=GCD(x.numerator,x.denominator);
	x.numerator/=gcd;
	x.denominator/=gcd;
}
fraction operator + (const fraction &x,const fraction &y)
{
	fraction z;
	ll gcd=GCD(x.denominator,y.denominator);
	z.denominator=x.denominator/gcd*y.denominator;
	z.numerator=x.numerator*(y.denominator/gcd)+y.numerator*(x.denominator/gcd);
	Reduction(z);
	return z;
}
fraction operator * (const fraction &x,const fraction &y)
{
	fraction z(x.numerator*y.numerator,x.denominator*y.denominator);
	Reduction(z);
	return z;
}
void operator += (fraction &x,const fraction &y)
{
	x=x+y;
}
ostream& operator << (ostream &os,const fraction &x)
{
	os<<x.numerator<<'/'<<x.denominator;
	return os;
}
char Get_Char()
{
	char c;
	do c=getchar(); while(c==' '||c=='\n'||c=='\r'||c=='\t');
	return c;
}
int n,m;
char map[M][M];
int main()
{
	int i,j;
	cin>>n>>m;
	for(i=1;i<=n;i++)
		for(j=1;j<=i;j++)
			map[i][j]=Get_Char();
	f[1][1]=fraction(1,1);
	for(i=1;i<=n;i++)
		for(j=1;j<=n;j++)
			if(map[i][j]=='*')
				f[i+1][j]+=f[i][j]*fraction(1,2),f[i+1][j+1]+=f[i][j]*fraction(1,2);
			else
				f[i+2][j+1]+=f[i][j];
	cout<<f[n+1][m+1];
}


BZOJ 1867 NOI1999 钉子和小球 动态规划