URAL 1114 Boxes

http://acm.timus.ru/problem.aspx?space=1&num=1114

Boxes

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.
input
2 1 1
output
9

题意

有N个盒子(1 ≤ N ≤ 20),有A个红球和B个蓝球(0 ≤ A ≤ 15,0 ≤ B ≤ 15),球都是一样的。把球放进盒子里,可以任意放,也可以不把所有的球都放进去,可以有盒子是空的。找出有多少种放球的方式。

这个是暴力法,直接五重循环,但是太麻烦了。我认为这个方法不太好,容易混了,看着看着就不知道到哪了。

#include
#include
#include
#include
using namespace std;
unsigned long long dp[21][21][21];
int main()
{
    int n,a,b,c,d,i,j,k;
    while(scanf("%d%d%d",&n,&a,&b)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        dp[0][0][0]=1;
        for(i=1;i<=n;i++)
            for(j=0;j<=a;j++)
            for(k=0;k<=b;k++)
            for(c=0;c<=j;c++)
            for(d=0;d<=k;d++)
            dp[i][j][k]+=dp[i-1][c][d];
        unsigned long long num=0;
        for(i=0;i<=a;i++)
            for(j=0;j<=b;j++)
            num+=dp[n][i][j];
        printf("%I64u\n",num);
    }
    return 0;
}

这个是先不要管蓝球,先看红球怎么放,这个用排列组合,就是从n+a中挑a个,然后再看蓝球,最后乘起来就可以。

#include 
#include 
#include 
#include 
using namespace std;
int main()
{
    int n,a,b,c;
    scanf("%d%d%d",&n,&a,&b);
    c=max(a,b);
    unsigned long long ans = 1, tmp = 1, sum = 0;
    for(int i=1;i<=c;i++)
    {
        tmp = tmp*(n+i)/i;
        sum = tmp;
        if (i==a) ans *= sum;
        if (i==b) ans *= sum;
    }

    printf("%I64u\n", ans);
}

这个是上面的方法的改进。

#include 
#include 
#include 
#include 
using namespace std;
unsigned long long f(int n,int m)
{
    unsigned long long v=1;
    for(int i=1;i<=n;i++)
        v=v*(m+i)/i;
    return v;
}
int main()
{
    int n,a,b;
    scanf("%d%d%d",&n,&a,&b);
    printf("%llu\n",f(n,a)*f(n,b));
}

你可能感兴趣的:(URAL 1114 Boxes)