CF261B Maxim and Restaurant

我的blog

题目链接:CF261B Maxim and Restaurant

[preface ]

背包DP+期望的一道题

[description ]

题目翻译有QwQ

[solution ]

我们要分两种情况讨论:

  • [sum_{i=1}^{n}a[i]leq p ]

  • [sum_{i=1}^{n}a[i]> p ]

对于情况(1),显然就是n个人都可以坐,那么直接输出(n)即可。

对于请款(2)

(f(i,j,k))表示表示已经处理完前i个人选了j个人占了k这么长的方案数,那么答案显然是:

[ans=dfrac{sum f(n,i,j) imes i! imes (n-i)!}{n!} ]

对于(f(i,j,k))我们有两个策略,一个是选,一个是不选,得出:

[f(i,j,k)=f(i-1,j-1,k-a[i])+f(i-1,j,k) ]

我们发现DP可以省掉一维

[code ]

#include <cstdio>
#include <algorithm>
#define ll long long
#define re register
using namespace std;
template<typename T>
inline void read(T&x)
{
	x=0;
	char s=(char)getchar();
	bool f=false;
	while(!(s>='0'&&s<='9'))
	{
		if(s=='-')
			f=true;
		s=(char)getchar();
	}
	while(s>='0'&&s<='9')
	{
		x=(x<<1)+(x<<3)+s-'0';
		s=(char)getchar();
	}
	if(f)
		x=(~x)+1;
}
const int N=55;
int n,p,a[N],sum;
long long dp[N][N];
double fac[N]= {1.0},ans;
int main()
{
	read(n);
	for(re int i=1; i<=n; ++i)
	{
		read(a[i]);
		sum+=a[i];
		fac[i]=fac[i-1]*i;
	}
	read(p);
	if(sum<=p)
	{
		printf("%lf
",(double)n);
		return 0;
	}
	dp[0][0]=1;
	for(re int i=1; i<=n; ++i)
		for(re int j=i; j>=1; --j)
			for(re int k=p; k>=a[i]; --k)
				dp[j][k]+=dp[j-1][k-a[i]];
	for(re int i=1; i<=n; ++i)
	{
		for(re int j=0; j<=p; ++j)
			printf("%lld ",dp[i][j]);
		putchar('
');
	}
	for(re int i=1; i<=n; ++i)
		for(re int j=0; j<=p; ++j)
			ans+=(double)dp[i][j]*fac[i]*fac[n-i];
	printf("%lf
",ans/fac[n]);
	return 0;
}
原文地址:https://www.cnblogs.com/wangjunrui/p/12512412.html