UVa 10780 - How do you add? (简单DP 组合数学 隔板法)

该博客介绍了UVa 10780编程问题,探讨如何通过动态规划(DP)和组合数学的隔板法解决将K个不超过N的非负整数相加得到总和N的不同方法数。文章提供了输入输出说明及样例,并解析了使用DP状态转移方程和隔板法求解的思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem A: How do you add?

Larry is very bad at math - he usually uses a calculator, which worked well throughout college. Unforunately, he is now struck in a deserted island with his good buddy Ryan after a snowboarding accident. They're now trying to spend some time figuring out some good problems, and Ryan will eat Larry if he cannot answer, so his fate is up to you!

It's a very simple problem - given a number N, how many ways can K numbers less than N add up to N?

For example, for N = 20 and K = 2, there are 21 ways:
0+20
1+19
2+18
3+17
4+16
5+15
...
18+2
19+1
20+0


Input

Each line will contain a pair of numbers N and KN and K will both be an integer from 1 to 100, inclusive. The input will terminate on 2 0's.

Output

Since Larry is only interested in the last few digits of the answer, for each pair of numbers N and K, print a single number mod 1,000,000 on a single line. 

Sample Input

20 2
20 2
0 0

Sample Output

21
21


题意:

把K个不超过N的非负整数加起来,使得他们的和为N,有多少种方法?


思路:

dp[i][j] 表示i个不超过N的非负整数加起来的和为j的方法数

则dp[i][j] = sum{ dp[i-1][j-p] } 表示当前这一位填p


也可以用组合数学来求 表示把N个球分到k个盒子,盒子可以为空

因为盒子可以为空 那么球数N加上K 就可以用隔板法来求了(求出的方案每一组减去1就是原来的问题,所以可以这么做),所以答案就是 C(N+K-1, K-1) 



#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>

using namespace std;

//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#define oform1 "%I64d"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#define oform1 "%lld"
#endif

#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define P64I1(a) printf(oform1, (a))
#define REP(i, n) for(int (i)=0; (i)<n; (i)++)
#define REP1(i, n) for(int (i)=1; (i)<=(n); (i)++)
#define FOR(i, s, t) for(int (i)=(s); (i)<=(t); (i)++)

const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));

const int maxn = 100 + 20;
const int MOD = 1000000;
int dp[maxn][maxn];

int main() {
    int N, K;

    while(scanf("%d%d", &N, &K) != EOF && (N || K)) {
        memset(dp, 0, sizeof(dp));
        dp[0][0] = 1;
        for(int i=1; i<=K; i++) {
            for(int j=0; j<=N; j++) {
                for(int p=0; p<=j; p++) {
                    dp[i][j] += dp[i-1][j-p];
                    if(dp[i][j] >= MOD) dp[i][j] -= MOD;
                }
            }
        }
        int ans = dp[K][N];
        printf("%d\n", ans);
    }

    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值