首页 > 编程语言 > 详细

C++9018:2323——分发小球

时间:2021-05-12 21:17:55      阅读:23      评论:0      收藏:0      [点我收藏+]

题目来自:http://218.5.5.242:9018/JudgeOnline/problem.php?id=2323

题目描述

把m相同个小球放在n个完全相同的盒子里,允许有的盒子为空,共有几种放法?(20>=m>=n)

输入

m n

样例输入

5 3

样例输出

0 0 5
0 1 4
0 2 3
1 1 3
1 2 2
5

提示

回溯

题目讲解:回溯DFS,非常好用,直接上代码:

#include <bits/stdc++.h>
using namespace std;

int n,m,tot = 0,a[21];
bool vis[21];

void search(int x,int t,int sum){
    if (x > n && sum == m){                // 输出解 
        tot++;
        for (int i = 1;i <= n;i++){
            cout << a[i];
            if (i != n) cout << " ";
        }
        cout << endl;
        return ;
    }
    if (x > n) return ;
    for (int i = t;i <= m - sum;i++){    // 字典序搜索,防止重复 
        vis[i] = true;
        a[x] = i;
        search(x+1,i,sum+i);
        vis[i] = false;
    }
}
int main(){
    memset(vis,false,sizeof(vis));
    cin >> m >> n;
    search(1,0,0);
    cout << tot;                        // 输出个数 
    return 0;
    
}

C++9018:2323——分发小球

原文:https://www.cnblogs.com/linyiweiblog/p/14761167.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!