题目:
N boxes are lined up in a sequence (1 ≤ N ≤ 20). You have A red balls and B blue balls (0 ≤ A ≤ 15, 0 ≤ B ≤ 15). The red balls (and the blue ones) are exactly the same. You can place the balls in the boxes. It is allowed to put in a box, balls of the two kinds, or only from one kind. You can also leave some of the boxes empty. It's not necessary to place all the balls in the boxes. Write a program, which finds the number of different ways to place the balls in the boxes in the described way.
Input
Input contains one line with three integers N, A and B separated by space.
Output
The result of your program must be an integer written on the only line of output.
Example
input | output |
---|---|
2 1 1 | 9 |
解题报告:题意很明确就是给定n个箱子,a个红球,b个蓝球,问总共有多少种方式,可放0-a个红球0-b个蓝球的数目。刚上来就去寻找数学规律,就是排列组合的plus版,会得出规律C(n-1,0)+C(n,1)+C(n+1,2)…….看上去很爽,每个式子的含义就是在有i个球的时候他所能放的数目,之后从0-a(0-b) 两次寻找累加求和之后做乘积麦克道最后结果。为什么会出现这个规律就是在给定的n个箱子面前 我要放i个相同的球,共有多少种方法。
ac代码:
#include<iostream>//排列组合
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef unsigned long long ll;
const int maxn=1e5+100;
int main()
{
int n,a,b,c;
cin>>n>>a>>b;
c=max(a,b);
n--;
ll ans=1,res=1,tmp=1;
for(int i=1;i<=c;i++)
{
tmp=tmp*(n+i)/i;
res+=tmp;
if(i==a) ans*=res;
if(i==b) ans*=res;
}
cout<<ans<<endl;
}
还有一种做法就是强行dp,因为数据范围不是很大,所以作死的强行dp,在为n的空间里,每次放t个球其中j个红球k个蓝球,进行存放数据。
ac代码:
#include<cstdio>//dp
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
typedef unsigned long long ull;
const int maxn=1e5+1000;
ull num[25][28];
int n,a,b;
int main()
{
while(cin>>n>>a>>b)
{
ull resa=0,resb=0;
for(int t=0;t<=a;t++)
{
memset(num,0,sizeof(num));
num[0][0]=1;
for(int i=0;i<=n;i++)
for(int j=0;j<=t;j++)
for(int k=0;k<=t-j;k++)
num[i+1][j+k]+=num[i][j];
resa+=num[n][t];
}
for(int t=0;t<=b;t++)
{
memset(num,0,sizeof(num));
num[0][0]=1;
for(int i=0;i<=n;i++)
for(int j=0;j<=t;j++)
for(int k=0;k<=t-j;k++)
num[i+1][j+k]+=num[i][j];
resb+=num[n][t];
}
cout<<resa*resb<<endl;
}
return 0;
}