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<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
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 <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
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 <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
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));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值