k種球若干,取n個球,輸出所有取球方案 (模擬)


有K種顏色的小球(K<=10),每種小球有若干個,總數小於100個。
現在有一個小盒子,能放N個小球(N<=8),現在要從這些小球里挑出N個小球,放滿盒子。
想知道有哪些挑選方式。注:每種顏色的小球之間沒有差別。

請按數字遞增順序輸出挑選小球的所有方式。

如有3種顏色,每種顏色小球的個數分別為a:1,b:2,c:3,挑出3個小球的挑法有:
003,012,021,102,111,120

 

#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<stack>
#include<numeric>
using namespace std;
struct node
{
    int num;
    vector< vector<int> > v;//兩個容器嵌套,記錄取球方案
};
int main()
{
    int n, k;
    cin >> k >> n;
    vector<node> ball(k);
    for (int i = 0; i < k; i++)
    {
        int t;
        cin >> t;
        ball[i].num = t;
    }
    if (k == 1)//只有一種方案
        cout << n << endl;
    else
    {
        vector<int>temp;
        for (int i = 0; i <= ball[0].num; i++)//初始化,第一種球的取法
        {
            temp.push_back(i);
            ball[0].v.push_back(temp);
            temp.clear();
        }
        for (int i = 1; i < k; i++)//取那種球
        {
            for (int j = 0; j < ball[i - 1].v.size(); j++)//取第i種球之前有幾種方案
            {
                for (int x = 0; x <= ball[i].num; x++)//第i種球可以取多少個
                {
                    temp = ball[i - 1].v[j];//取第i-1種球的第j種方案
                    temp.push_back(x);//第i種球取x個
                    if (i == k - 1)//取完K種球並且球的總數為N(k-1是因為第一種球初始化處理了)
                    {
                        if (accumulate(temp.begin(), temp.end(),0) == n)//輸出方案
                        {
                            for (int y = 0; y < temp.size(); y++)
                                cout << temp[y];
                            cout << endl;
                        }
                    }
                    else
                        if (accumulate(temp.begin(), temp.end(),0) <= n)
                            ball[i].v.push_back(temp);//取完第i種球之后的取球方案
                    temp.clear();
                }
            }
        }
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM